<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>8 The Web Layer 3.2.11</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <link rel="stylesheet" href="../css/main.css" type="text/css" media="screen, print" title="Style" charset="utf-8"/>
    <link rel="stylesheet" href="../css/pdf.css" type="text/css" media="print" title="PDF" charset="utf-8"/>
    <script type="text/javascript">
function addJsClass() {
    var classes = document.body.className.split(" ");
    classes.push("js");
    document.body.className = classes.join(" ");
}
    </script>
</head>

<body class="body" onload="addJsClass();">
<div id="navigation">
    <div class="navTitle">
        
        The Grails Framework
    </div>
    <div class="navLinks">
        <ul>
            <li>
                <div id="nav-summary" onmouseover="toggleNavSummary(false)" onmouseout="toggleNavSummary(true)">
                    <a href="../guide/index.html" class="button">Table of contents</a>

                    <div id="nav-summary-childs" style="display:none;">
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/introduction.html"><strong>1</strong><span>Introduction</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/gettingStarted.html"><strong>2</strong><span>Getting Started</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/upgrading.html"><strong>3</strong><span>Upgrading</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/conf.html"><strong>4</strong><span>Configuration</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/commandLine.html"><strong>5</strong><span>The Command Line</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/profiles.html"><strong>6</strong><span>Application Profiles</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/GORM.html"><strong>7</strong><span>Object Relational Mapping (GORM)</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/theWebLayer.html"><strong>8</strong><span>The Web Layer</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/traits.html"><strong>9</strong><span>Traits</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/webServices.html"><strong>10</strong><span>Web Services</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/async.html"><strong>11</strong><span>Asynchronous Programming</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/validation.html"><strong>12</strong><span>Validation</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/services.html"><strong>13</strong><span>The Service Layer</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/staticTypeCheckingAndCompilation.html"><strong>14</strong><span>Static Type Checking And Compilation</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/testing.html"><strong>15</strong><span>Testing</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/i18n.html"><strong>16</strong><span>Internationalization</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/security.html"><strong>17</strong><span>Security</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/plugins.html"><strong>18</strong><span>Plugins</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/spring.html"><strong>19</strong><span>Grails and Spring</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/hibernate.html"><strong>20</strong><span>Grails and Hibernate</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/scaffolding.html"><strong>21</strong><span>Scaffolding</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/deployment.html"><strong>22</strong><span>Deployment</span></a>
                        </div>
                        
                        <div class="toc-item" style="margin-left:0"><a href="../guide/contributing.html"><strong>23</strong><span>Contributing to Grails</span></a>
                        </div>
                        
                    </div>
                </div>
            </li>
            <li class="separator selected">
                <a id="ref-button" onclick="localToggle(); return false;" href="#">Quick Reference</a>
            </li>
        </ul>
    </div>


</div>

<table id="colset" border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td id="col1">
            <div id="main" class="corner-all">

                
                    <div class="toc-item prev-left"><a href="../guide/GORM.html">&lt;&lt; <strong>7</strong><span>Object Relational Mapping (GORM)</span></a></div>
                

                <span id='toggle-col1' class="toggle">(<a href="#" onclick="localToggle(); return false;">Quick Reference</a>)</span>

                
                    <div class="toc-item next-right"><a href="../guide/traits.html"><strong>9</strong><span>Traits</span> >></a></div>
                


                <div class="project">
                    <h1>8 The Web Layer</h1>

                    <p><strong>Version:</strong> 3.2.11</p>
                </div>

                
                <div id="table-of-content">
                    <h2>Table of Contents</h2>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#controllers"><strong>8.1</strong><span>Controllers</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#understandingControllersAndActions"><strong>8.1.1</strong><span>Understanding Controllers and Actions</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#controllersAndScopes"><strong>8.1.2</strong><span>Controllers and Scopes</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#modelsAndViews"><strong>8.1.3</strong><span>Models and Views</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#redirectsAndChaining"><strong>8.1.4</strong><span>Redirects and Chaining</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#dataBinding"><strong>8.1.5</strong><span>Data Binding</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#jsonResponses"><strong>8.1.6</strong><span>Responding with JSON</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#moreOnJSONBuilder"><strong>8.1.7</strong><span>More on JSONBuilder</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#xmlResponses"><strong>8.1.8</strong><span>Responding with XML</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#uploadingFiles"><strong>8.1.9</strong><span>Uploading Files</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#commandObjects"><strong>8.1.10</strong><span>Command Objects</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#formtokens"><strong>8.1.11</strong><span>Handling Duplicate Form Submissions</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#typeConverters"><strong>8.1.12</strong><span>Simple Type Converters</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#controllerExceptionHandling"><strong>8.1.13</strong><span>Declarative Controller Exception Handling</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#gsp"><strong>8.2</strong><span>Groovy Server Pages</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#GSPBasics"><strong>8.2.1</strong><span>GSP Basics</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#variablesAndScopes"><strong>8.2.1.1</strong><span>Variables and Scopes</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#logicAndIteration"><strong>8.2.1.2</strong><span>Logic and Iteration</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#pageDirectives"><strong>8.2.1.3</strong><span>Page Directives</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#expressions"><strong>8.2.1.4</strong><span>Expressions</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#tags"><strong>8.2.2</strong><span>GSP Tags</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#tagVariablesAndScopes"><strong>8.2.2.1</strong><span>Variables and Scopes</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#tagLogicAndIteration"><strong>8.2.2.2</strong><span>Logic and Iteration</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#searchAndFiltering"><strong>8.2.2.3</strong><span>Search and Filtering</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#linksAndResources"><strong>8.2.2.4</strong><span>Links and Resources</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#formsAndFields"><strong>8.2.2.5</strong><span>Forms and Fields</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#tagsAsMethodCalls"><strong>8.2.2.6</strong><span>Tags as Method Calls</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#viewsAndTemplates"><strong>8.2.3</strong><span>Views and Templates</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#layouts"><strong>8.2.4</strong><span>Layouts with Sitemesh</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#resources"><strong>8.2.5</strong><span>Static Resources</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#sitemeshContentBlocks"><strong>8.2.6</strong><span>Sitemesh Content Blocks</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#makingChangesToADeployedApplication"><strong>8.2.7</strong><span>Making Changes to a Deployed Application</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#GSPDebugging"><strong>8.2.8</strong><span>GSP Debugging</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#taglibs"><strong>8.3</strong><span>Tag Libraries</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#taglibVariablesAndScopes"><strong>8.3.1</strong><span>Variables and Scopes</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#simpleTags"><strong>8.3.2</strong><span>Simple Tags</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#logicalTags"><strong>8.3.3</strong><span>Logical Tags</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#iterativeTags"><strong>8.3.4</strong><span>Iterative Tags</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#namespaces"><strong>8.3.5</strong><span>Tag Namespaces</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#usingJSPTagLibraries"><strong>8.3.6</strong><span>Using JSP Tag Libraries</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#tagReturnValue"><strong>8.3.7</strong><span>Tag return value</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#urlmappings"><strong>8.4</strong><span>URL Mappings</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#mappingToControllersAndActions"><strong>8.4.1</strong><span>Mapping to Controllers and Actions</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#restfulMappings"><strong>8.4.2</strong><span>Mapping to REST resources</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#redirectMappings"><strong>8.4.3</strong><span>Redirects In URL Mappings</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#embeddedVariables"><strong>8.4.4</strong><span>Embedded Variables</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#mappingToViews"><strong>8.4.5</strong><span>Mapping to Views</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#mappingToResponseCodes"><strong>8.4.6</strong><span>Mapping to Response Codes</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#mappingHTTP"><strong>8.4.7</strong><span>Mapping to HTTP methods</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#mappingWildcards"><strong>8.4.8</strong><span>Mapping Wildcards</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#automaticLinkRewriting"><strong>8.4.9</strong><span>Automatic Link Re-Writing</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#applyingConstraints"><strong>8.4.10</strong><span>Applying Constraints</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#namedMappings"><strong>8.4.11</strong><span>Named URL Mappings</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#customizingUrlFormat"><strong>8.4.12</strong><span>Customizing URL Formats</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#namespacedControllers"><strong>8.4.13</strong><span>Namespaced Controllers</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#cors"><strong>8.5</strong><span>CORS</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#interceptors"><strong>8.6</strong><span>Interceptors</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#definingInterceptors"><strong>8.6.1</strong><span>Defining Interceptors</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#interceptorMatching"><strong>8.6.2</strong><span>Matching Requests with Inteceptors</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#interceptorOrdering"><strong>8.6.3</strong><span>Ordering Interceptor Execution</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#contentNegotiation"><strong>8.7</strong><span>Content Negotiation</span></a>
                    </div>
                    
                </div>
                

                
<a name="7. The Web Layer"><!-- Legacy link --></a>
<h1 id="theWebLayer">8 The Web Layer</h1>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>




<a name="7.1 Controllers"><!-- Legacy link --></a>
<h2 id="controllers">8.1 Controllers</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>A controller handles requests and creates or prepares the response. A controller can generate the response directly or delegate to a view. To create a controller, simply create a class whose name ends with <code>Controller</code> in the <code>grails-app/controllers</code> directory (in a subdirectory if it&#8217;s in a package).</p>
</div>
<div class="paragraph">
<p>The default <a href="#urlmappings">URL Mapping</a> configuration ensures that the first part of your controller name is mapped to a URI and each action defined within your controller maps to URIs within the controller name URI.</p>
</div>

<a name="7.1.1 Understanding Controllers and Actions"><!-- Legacy link --></a>
<h2 id="understandingControllersAndActions">8.1.1 Understanding Controllers and Actions</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/understandingControllersAndActions.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_creating_a_controller">Creating a controller</h4>
<div class="paragraph">
<p>Controllers can be created with the <a href="../ref/Command%20Line/create-controller.html">create-controller</a> or <a href="../ref/Command%20Line/generate-controller.html">generate-controller</a> command. For example try running the following command from the root of a Grails project:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails create-controller book</code></pre>
</div>
</div>
<div class="paragraph">
<p>The command will create a controller at the location <code>grails-app/controllers/myapp/BookController.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> myapp

<span class="type">class</span> <span class="class">BookController</span> {

    <span class="keyword">def</span> <span class="function">index</span>() { }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>where "myapp" will be the name of your application, the default package name if one isn&#8217;t specified.</p>
</div>
<div class="paragraph">
<p><code>BookController</code> by default maps to the /book URI (relative to your application root).</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The <code>create-controller</code> and <code>generate-controller</code> commands are just for convenience and you can just as easily create controllers using your favorite text editor or IDE
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_creating_actions">Creating Actions</h4>
<div class="paragraph">
<p>A controller can have multiple public action methods; each one maps to a URI:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {

    <span class="keyword">def</span> <span class="function">list</span>() {

        <span class="comment">// do controller logic</span>
        <span class="comment">// create model</span>

        <span class="keyword">return</span> model
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This example maps to the <code>/book/list</code> URI by default thanks to the property being named <code>list</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_the_default_action">The Default Action</h4>
<div class="paragraph">
<p>A controller has the concept of a default URI that maps to the root URI of the controller, for example <code>/book</code> for <code>BookController</code>. The action that is called when the default URI is requested is dictated by the following rules:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>If there is only one action, it&#8217;s the default</p>
</li>
<li>
<p>If you have an action named <code>index</code>, it&#8217;s the default</p>
</li>
<li>
<p>Alternatively you can set it explicitly with the <code>defaultAction</code> property:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> defaultAction = <span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
</div>

<a name="7.1.2 Controllers and Scopes"><!-- Legacy link --></a>
<h2 id="controllersAndScopes">8.1.2 Controllers and Scopes</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/controllersAndScopes.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_available_scopes">Available Scopes</h4>
<div class="paragraph">
<p>Scopes are hash-like objects where you can store variables. The following scopes are available to controllers:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="../ref/Controllers/servletContext.html">servletContext</a> - Also known as application scope, this scope lets you share state across the entire web application. The servletContext is an instance of <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html">ServletContext</a></p>
</li>
<li>
<p><a href="../ref/Controllers/session.html">session</a> - The session allows associating state with a given user and typically uses cookies to associate a session with a client. The session object is an instance of <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSession.html">HttpSession</a></p>
</li>
<li>
<p><a href="../ref/Controllers/request.html">request</a> - The request object allows the storage of objects for the current request only. The request object is an instance of <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html">HttpServletRequest</a></p>
</li>
<li>
<p><a href="../ref/Controllers/params.html">params</a> - Mutable map of incoming request query string or POST parameters</p>
</li>
<li>
<p><a href="../ref/Controllers/flash.html">flash</a> - See below</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_accessing_scopes">Accessing Scopes</h4>
<div class="paragraph">
<p>Scopes can be accessed using the variable names above in combination with Groovy&#8217;s array index operator, even on classes provided by the Servlet API such as the <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html">HttpServletRequest</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
    <span class="keyword">def</span> <span class="function">find</span>() {
        <span class="keyword">def</span> findBy = params[<span class="string"><span class="delimiter">&quot;</span><span class="content">findBy</span><span class="delimiter">&quot;</span></span>]
        <span class="keyword">def</span> appContext = request[<span class="string"><span class="delimiter">&quot;</span><span class="content">foo</span><span class="delimiter">&quot;</span></span>]
        <span class="keyword">def</span> loggedUser = session[<span class="string"><span class="delimiter">&quot;</span><span class="content">logged_user</span><span class="delimiter">&quot;</span></span>]
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also access values within scopes using the de-reference operator, making the syntax even more clear:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
    <span class="keyword">def</span> <span class="function">find</span>() {
        <span class="keyword">def</span> findBy = params.findBy
        <span class="keyword">def</span> appContext = request.foo
        <span class="keyword">def</span> loggedUser = session.logged_user
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is one of the ways that Grails unifies access to the different scopes.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_flash_scope">Using Flash Scope</h4>
<div class="paragraph">
<p>Grails supports the concept of <a href="../ref/Controllers/flash.html">flash</a> scope as a temporary store to make attributes available for this request and the next request only. Afterwards the attributes are cleared. This is useful for setting a message directly before redirecting, for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">delete</span>() {
    <span class="keyword">def</span> b = <span class="predefined-type">Book</span>.get(params.id)
    <span class="keyword">if</span> (!b) {
        flash.message = <span class="string"><span class="delimiter">&quot;</span><span class="content">User not found for id </span><span class="inline"><span class="inline-delimiter">${</span>params.id<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
        redirect(<span class="key">action</span>:list)
    }
    ... <span class="comment">// remaining code</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When the <code>delete</code> action is requested, the <code>message</code> value will be in scope and can be used to display an information message. It will be removed from the <code>flash</code> scope after this second request.</p>
</div>
<div class="paragraph">
<p>Note that the attribute name can be anything you want, and the values are often strings used to display messages, but can be any object type.</p>
</div>
</div>
<div class="sect3">
<h4 id="_scoped_controllers">Scoped Controllers</h4>
<div class="paragraph">
<p>Newly created applications have the <code>grails.controllers.defaultScope</code> property set to a value of "singleton" in <code>application.yml</code>.  You may change this value to any
of the supported scopes listed below.  If the property is not assigned a value at all, controllers will default to "prototype" scope.</p>
</div>
<div class="paragraph">
<p>Supported controller scopes are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>prototype</code> (default) - A new controller will be created for each request (recommended for actions as Closure properties)</p>
</li>
<li>
<p><code>session</code> - One controller is created for the scope of a user session</p>
</li>
<li>
<p><code>singleton</code> - Only one instance of the controller ever exists (recommended for actions as methods)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>To enable one of the scopes, add a static <code>scope</code> property to your class with one of the valid scope values listed above, for example</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> scope = <span class="string"><span class="delimiter">&quot;</span><span class="content">singleton</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>You can define the default strategy in <code>application.yml</code> with the <code>grails.controllers.defaultScope</code> key, for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">grails</span>:
    <span class="key">controllers</span>:
        <span class="key">defaultScope</span>: singleton</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Use scoped controllers wisely. For instance, we don&#8217;t recommend having any properties in a singleton-scoped controller since they will be shared for <em>all</em> requests.
</td>
</tr>
</table>
</div>
</div>

<a name="7.1.3 Models and Views"><!-- Legacy link --></a>
<h2 id="modelsAndViews">8.1.3 Models and Views</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/modelsAndViews.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_returning_the_model">Returning the Model</h4>
<div class="paragraph">
<p>A model is a Map that the view uses when rendering. The keys within that Map correspond to variable names accessible by the view. There are a couple of ways to return a model. First, you can explicitly return a Map instance:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>() {
    [<span class="key">book</span>: <span class="predefined-type">Book</span>.get(params.id)]
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The above does <em>not</em> reflect what you should use with the scaffolding views - see the <a href="scaffolding.html">scaffolding section</a> for more details.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>A more advanced approach is to return an instance of the Spring <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/ModelAndView.html">ModelAndView</a> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">org.springframework.web.servlet.ModelAndView</span>

<span class="keyword">def</span> <span class="function">index</span>() {
    <span class="comment">// get some books just for the index page, perhaps your favorites</span>
    <span class="keyword">def</span> favoriteBooks = ...

    <span class="comment">// forward to the list view to show them</span>
    <span class="keyword">return</span> <span class="keyword">new</span> ModelAndView(<span class="string"><span class="delimiter">&quot;</span><span class="content">/book/list</span><span class="delimiter">&quot;</span></span>, [ bookList : favoriteBooks ])
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>One thing to bear in mind is that certain variable names can not be used in your model:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>attributes</code></p>
</li>
<li>
<p><code>application</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Currently, no error will be reported if you do use them, but this will hopefully change in a future version of Grails.</p>
</div>
</div>
<div class="sect3">
<h4 id="_selecting_the_view">Selecting the View</h4>
<div class="paragraph">
<p>In both of the previous two examples there was no code that specified which <a href="#gsp">view</a> to render. So how does Grails know which one to pick? The answer lies in the conventions. Grails will look for a view at the location <code>grails-app/views/book/show.gsp</code> for this <code>show</code> action:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
    <span class="keyword">def</span> <span class="function">show</span>() {
         [<span class="key">book</span>: <span class="predefined-type">Book</span>.get(params.id)]
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To render a different view, use the <a href="../ref/Controllers/render.html">render</a> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>() {
    <span class="keyword">def</span> map = [<span class="key">book</span>: <span class="predefined-type">Book</span>.get(params.id)]
    render(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">display</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: map)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case Grails will attempt to render a view at the location <code>grails-app/views/book/display.gsp</code>. Notice that Grails automatically qualifies the view location with the <code>book</code> directory of the <code>grails-app/views</code> directory. This is convenient, but to access shared views, you use an absolute path instead of a relative one:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>() {
    <span class="keyword">def</span> map = [<span class="key">book</span>: <span class="predefined-type">Book</span>.get(params.id)]
    render(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/shared/display</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: map)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case Grails will attempt to render a view at the location <code>grails-app/views/shared/display.gsp</code>.</p>
</div>
<div class="paragraph">
<p>Grails also supports JSPs as views, so if a GSP isn&#8217;t found in the expected location but a JSP is, it will be used instead.</p>
</div>
</div>
<div class="sect3">
<h4 id="_selecting_views_for_namespaced_controllers">Selecting Views For Namespaced Controllers</h4>
<div class="paragraph">
<p>If a controller defines a namespace for itself with the <a href="#namespacedControllers">namespace</a> property that will affect the root directory in which Grails will look for views which are specified with a relative path.  The default root directory for views rendered by a namespaced controller is <code>grails-app/views/&lt;namespace name&gt;/&lt;controller name&gt;/</code>.  If the view is not found in the namespaced directory then Grails will fallback to looking for the view in the non-namespaced directory.</p>
</div>
<div class="paragraph">
<p>See the example below.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ReportingController</span> {
    <span class="directive">static</span> namespace = <span class="string"><span class="delimiter">'</span><span class="content">business</span><span class="delimiter">'</span></span>

    <span class="keyword">def</span> <span class="function">humanResources</span>() {
        <span class="comment">// This will render grails-app/views/business/reporting/humanResources.gsp</span>
        <span class="comment">// if it exists.</span>

        <span class="comment">// If grails-app/views/business/reporting/humanResources.gsp does not</span>
        <span class="comment">// exist the fallback will be grails-app/views/reporting/humanResources.gsp.</span>

        <span class="comment">// The namespaced GSP will take precedence over the non-namespaced GSP.</span>

        [<span class="key">numberOfEmployees</span>: <span class="integer">9</span>]
    }


    <span class="keyword">def</span> <span class="function">accountsReceivable</span>() {
        <span class="comment">// This will render grails-app/views/business/reporting/numberCrunch.gsp</span>
        <span class="comment">// if it exists.</span>

        <span class="comment">// If grails-app/views/business/reporting/numberCrunch.gsp does not</span>
        <span class="comment">// exist the fallback will be grails-app/views/reporting/numberCrunch.gsp.</span>

        <span class="comment">// The namespaced GSP will take precedence over the non-namespaced GSP.</span>

        render <span class="key">view</span>: <span class="string"><span class="delimiter">'</span><span class="content">numberCrunch</span><span class="delimiter">'</span></span>, <span class="key">model</span>: [<span class="key">numberOfEmployees</span>: <span class="integer">13</span>]
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_rendering_a_response">Rendering a Response</h4>
<div class="paragraph">
<p>Sometimes it&#8217;s easier (for example with Ajax applications) to render snippets of text or code to the response directly from the controller. For this, the highly flexible <code>render</code> method can be used:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">render <span class="string"><span class="delimiter">&quot;</span><span class="content">Hello World!</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The above code writes the text "Hello World!" to the response. Other examples include:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// write some markup</span>
render {
   <span class="keyword">for</span> (b <span class="keyword">in</span> books) {
      div(<span class="key">id</span>: b.id, b.title)
   }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// render a specific view</span>
render(<span class="key">view</span>: <span class="string"><span class="delimiter">'</span><span class="content">show</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// render a template for each item in a collection</span>
render(<span class="key">template</span>: <span class="string"><span class="delimiter">'</span><span class="content">book_template</span><span class="delimiter">'</span></span>, <span class="key">collection</span>: <span class="predefined-type">Book</span>.list())</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// render some text with encoding and content type</span>
render(<span class="key">text</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">&lt;xml&gt;some xml&lt;/xml&gt;</span><span class="delimiter">&quot;</span></span>, <span class="key">contentType</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">text/xml</span><span class="delimiter">&quot;</span></span>, <span class="key">encoding</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">UTF-8</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you plan on using Groovy&#8217;s <code>MarkupBuilder</code> to generate HTML for use with the <code>render</code> method be careful of naming clashes between HTML elements and Grails tags, for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">groovy.xml.MarkupBuilder</span>
...
def login() {
    <span class="keyword">def</span> writer = <span class="keyword">new</span> <span class="predefined-type">StringWriter</span>()
    <span class="keyword">def</span> builder = <span class="keyword">new</span> MarkupBuilder(writer)
    builder.html {
        head {
            title <span class="string"><span class="delimiter">'</span><span class="content">Log in</span><span class="delimiter">'</span></span>
        }
        body {
            h1 <span class="string"><span class="delimiter">'</span><span class="content">Hello</span><span class="delimiter">'</span></span>
            form {
            }
        }
    }

    <span class="keyword">def</span> html = writer.toString()
    render html
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will actually <a href="#tagsAsMethodCalls">call the form tag</a> (which will return some text that will be ignored by the <code>MarkupBuilder</code>). To correctly output a <code>&lt;form&gt;</code> element, use the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">login</span>() {
    <span class="comment">// ...</span>
    body {
        h1 <span class="string"><span class="delimiter">'</span><span class="content">Hello</span><span class="delimiter">'</span></span>
        builder.form {
        }
    }
    <span class="comment">// ...</span>
}</code></pre>
</div>
</div>
</div>

<a name="7.1.4 Redirects and Chaining"><!-- Legacy link --></a>
<h2 id="redirectsAndChaining">8.1.4 Redirects and Chaining</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/redirectsAndChaining.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_redirects">Redirects</h4>
<div class="paragraph">
<p>Actions can be redirected using the <a href="../ref/Controllers/redirect.html">redirect</a> controller method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">OverviewController</span> {

    <span class="keyword">def</span> <span class="function">login</span>() {}

    <span class="keyword">def</span> <span class="function">find</span>() {
        <span class="keyword">if</span> (!session.user)
            redirect(<span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">login</span><span class="delimiter">'</span></span>)
            <span class="keyword">return</span>
        }
        ...
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Internally the <a href="../ref/Controllers/redirect.html">redirect</a> method uses the <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletResponse.html">HttpServletResponse</a> object&#8217;s <code>sendRedirect</code> method.</p>
</div>
<div class="paragraph">
<p>The <code>redirect</code> method expects one of:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The name of an action (and controller name if the redirect isn&#8217;t to an action in the current controller):</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Also redirects to the index action in the home controller</span>
redirect(<span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">home</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">index</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>A URI for a resource relative the application context path:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Redirect to an explicit URI</span>
redirect(<span class="key">uri</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/login.html</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Or a full URL:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Redirect to a URL</span>
redirect(<span class="key">url</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://grails.org</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>A <a href="GORM.html">domain class</a> instance:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Redirect to the domain instance</span>
<span class="predefined-type">Book</span> book = ... <span class="comment">// obtain a domain instance</span>
redirect book</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the above example Grails will construct a link using the domain class <code>id</code> (if present).</p>
</div>
<div class="paragraph">
<p>Parameters can optionally be passed from one action to the next using the <code>params</code> argument of the method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">redirect(<span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">myaction</span><span class="delimiter">'</span></span>, <span class="key">params</span>: [<span class="key">myparam</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">myvalue</span><span class="delimiter">&quot;</span></span>])</code></pre>
</div>
</div>
<div class="paragraph">
<p>These parameters are made available through the <a href="../ref/Controllers/params.html">params</a> dynamic property that accesses request parameters. If a parameter is specified with the same name as a request parameter, the request parameter is overridden and the controller parameter is used.</p>
</div>
<div class="paragraph">
<p>Since the <code>params</code> object is a Map, you can use it to pass the current request parameters from one action to the next:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">redirect(<span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">next</span><span class="delimiter">&quot;</span></span>, <span class="key">params</span>: params)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Finally, you can also include a fragment in the target URI:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">redirect(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">test</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>, <span class="key">fragment</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">profile</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>which will (depending on the URL mappings) redirect to something like "/myapp/test/show#profile".</p>
</div>
</div>
<div class="sect3">
<h4 id="_chaining">Chaining</h4>
<div class="paragraph">
<p>Actions can also be chained. Chaining allows the model to be retained from one action to the next. For example calling the <code>first</code> action in this action:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ExampleChainController</span> {

    <span class="keyword">def</span> <span class="function">first</span>() {
        chain(<span class="key">action</span>: second, <span class="key">model</span>: [<span class="key">one</span>: <span class="integer">1</span>])
    }

    <span class="keyword">def</span> <span class="function">second</span> () {
        chain(<span class="key">action</span>: third, <span class="key">model</span>: [<span class="key">two</span>: <span class="integer">2</span>])
    }

    <span class="keyword">def</span> <span class="function">third</span>() {
        [<span class="key">three</span>: <span class="integer">3</span>])
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>results in the model:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">[<span class="key">one</span>: <span class="integer">1</span>, <span class="key">two</span>: <span class="integer">2</span>, <span class="key">three</span>: <span class="integer">3</span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The model can be accessed in subsequent controller actions in the chain using the <code>chainModel</code> map. This dynamic property only exists in actions following the call to the <code>chain</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ChainController</span> {

    <span class="keyword">def</span> <span class="function">nextInChain</span>() {
        <span class="keyword">def</span> model = chainModel.myModel
        ...
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Like the <code>redirect</code> method you can also pass parameters to the <code>chain</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">chain(<span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">action1</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: [<span class="key">one</span>: <span class="integer">1</span>], <span class="key">params</span>: [<span class="key">myparam</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">param1</span><span class="delimiter">&quot;</span></span>])</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The chain method uses the HTTP session and hence should only be used if your application is stateful.
</td>
</tr>
</table>
</div>
</div>

<a name="7.1.6 Data Binding"><!-- Legacy link --></a>
<h2 id="dataBinding">8.1.5 Data Binding</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/dataBinding.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Data binding is the act of "binding" incoming request parameters onto the properties of an object or an entire graph of objects. Data binding should deal with all necessary type conversion since request parameters, which are typically delivered by a form submission, are always strings whilst the properties of a Groovy or Java object may well not be.</p>
</div>
<div class="sect3">
<h4 id="_map_based_binding">Map Based Binding</h4>
<div class="paragraph">
<p>The data binder is capable of converting and assigning values in a Map to properties of an object.  The binder will associate entries in the Map to properties of the object using the keys in the Map that have values which correspond to property names on the object.  The following code demonstrates the basics:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/domain/Person.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Person</span> {
    <span class="predefined-type">String</span> firstName
    <span class="predefined-type">String</span> lastName
    <span class="predefined-type">Integer</span> age
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">firstName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>, <span class="key">lastName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>, <span class="key">age</span>: <span class="integer">63</span>]

<span class="keyword">def</span> person = <span class="keyword">new</span> Person(bindingMap)

<span class="keyword">assert</span> person.firstName == <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.lastName == <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.age == <span class="integer">63</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>To update properties of a domain object you may assign a Map to the <code>properties</code> property of the domain class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">firstName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>, <span class="key">lastName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>, <span class="key">age</span>: <span class="integer">63</span>]

<span class="keyword">def</span> person = Person.get(someId)
person.properties = bindingMap

<span class="keyword">assert</span> person.firstName == <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.lastName == <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.age == <span class="integer">63</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The binder can populate a full graph of objects using Maps of Maps.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Person</span> {
    <span class="predefined-type">String</span> firstName
    <span class="predefined-type">String</span> lastName
    <span class="predefined-type">Integer</span> age
    Address homeAddress
}

<span class="type">class</span> <span class="class">Address</span> {
    <span class="predefined-type">String</span> county
    <span class="predefined-type">String</span> country
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">firstName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>, <span class="key">lastName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>, <span class="key">age</span>: <span class="integer">63</span>, <span class="key">homeAddress</span>: [<span class="key">county</span>: <span class="string"><span class="delimiter">'</span><span class="content">Surrey</span><span class="delimiter">'</span></span>, <span class="key">country</span>: <span class="string"><span class="delimiter">'</span><span class="content">England</span><span class="delimiter">'</span></span>] ]

<span class="keyword">def</span> person = <span class="keyword">new</span> Person(bindingMap)

<span class="keyword">assert</span> person.firstName == <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.lastName == <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.age == <span class="integer">63</span>
<span class="keyword">assert</span> person.homeAddress.county == <span class="string"><span class="delimiter">'</span><span class="content">Surrey</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.homeAddress.country == <span class="string"><span class="delimiter">'</span><span class="content">England</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_binding_to_collections_and_maps">Binding To Collections And Maps</h4>
<div class="paragraph">
<p>The data binder can populate and update Collections and Maps.  The following code shows a simple example of populating a <code>List</code> of objects in a domain class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Band</span> {
    <span class="predefined-type">String</span> name
    <span class="directive">static</span> hasMany = [<span class="key">albums</span>: Album]
    <span class="predefined-type">List</span> albums
}

<span class="type">class</span> <span class="class">Album</span> {
    <span class="predefined-type">String</span> title
    <span class="predefined-type">Integer</span> numberOfTracks
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Genesis</span><span class="delimiter">'</span></span>,
                  <span class="string"><span class="delimiter">'</span><span class="content">albums[0]</span><span class="delimiter">'</span></span>: [<span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">Foxtrot</span><span class="delimiter">'</span></span>, <span class="key">numberOfTracks</span>: <span class="integer">6</span>],
                  <span class="string"><span class="delimiter">'</span><span class="content">albums[1]</span><span class="delimiter">'</span></span>: [<span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">Nursery Cryme</span><span class="delimiter">'</span></span>, <span class="key">numberOfTracks</span>: <span class="integer">7</span>]]

<span class="keyword">def</span> band = <span class="keyword">new</span> Band(bindingMap)

<span class="keyword">assert</span> band.name == <span class="string"><span class="delimiter">'</span><span class="content">Genesis</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> band.albums.size() == <span class="integer">2</span>
<span class="keyword">assert</span> band.albums[<span class="integer">0</span>].title == <span class="string"><span class="delimiter">'</span><span class="content">Foxtrot</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> band.albums[<span class="integer">0</span>].numberOfTracks == <span class="integer">6</span>
<span class="keyword">assert</span> band.albums[<span class="integer">1</span>].title == <span class="string"><span class="delimiter">'</span><span class="content">Nursery Cryme</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> band.albums[<span class="integer">1</span>].numberOfTracks == <span class="integer">7</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That code would work in the same way if <code>albums</code> were an array instead of a <code>List</code>.</p>
</div>
<div class="paragraph">
<p>Note that when binding to a <code>Set</code> the structure of the <code>Map</code> being bound to the <code>Set</code> is the same as that of a <code>Map</code> being bound to a <code>List</code> but since a <code>Set</code> is unordered, the indexes don&#8217;t necessarily correspond to the order of elements in the <code>Set</code>.  In the code example above, if <code>albums</code> were a <code>Set</code> instead of a <code>List</code>, the <code>bindingMap</code> could look exactly the same but 'Foxtrot' might be the first album in the <code>Set</code> or it might be the second.  When updating existing elements in a <code>Set</code> the <code>Map</code> being assigned to the <code>Set</code> must have <code>id</code> elements in it which represent the element in the <code>Set</code> being updated, as in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">/*
 * The value of the indexes 0 and 1 in albums[0] and albums[1] are arbitrary
 * values that can be anything as long as they are unique within the Map.
 * They do not correspond to the order of elements in albums because albums
 * is a Set.
 */</span>
<span class="keyword">def</span> bindingMap = [<span class="string"><span class="delimiter">'</span><span class="content">albums[0]</span><span class="delimiter">'</span></span>: [<span class="key">id</span>: <span class="integer">9</span>, <span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>]
                  <span class="string"><span class="delimiter">'</span><span class="content">albums[1]</span><span class="delimiter">'</span></span>: [<span class="key">id</span>: <span class="integer">4</span>, <span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">Selling England By The Pound</span><span class="delimiter">'</span></span>]]

<span class="keyword">def</span> band = Band.get(someBandId)

<span class="comment">/*
 * This will find the Album in albums that has an id of 9 and will set its title
 * to 'The Lamb Lies Down On Broadway' and will find the Album in albums that has
 * an id of 4 and set its title to 'Selling England By The Pound'.  In both
 * cases if the Album cannot be found in albums then the album will be retrieved
 * from the database by id, the Album will be added to albums and will be updated
 * with the values described above.  If a Album with the specified id cannot be
 * found in the database, then a binding error will be created and associated
 * with the band object.  More on binding errors later.
 */</span>
band.properties = bindingMap</code></pre>
</div>
</div>
<div class="paragraph">
<p>When binding to a <code>Map</code> the structure of the binding <code>Map</code> is the same as the structure of a <code>Map</code> used for binding to a <code>List</code> or a <code>Set</code> and the index inside of square brackets corresponds to the key in the <code>Map</code> being bound to.  See the following code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Album</span> {
    <span class="predefined-type">String</span> title
    <span class="directive">static</span> hasMany = [<span class="key">players</span>: Player]
    <span class="predefined-type">Map</span> players
}

<span class="type">class</span> <span class="class">Player</span> {
    <span class="predefined-type">String</span> name
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>,
                  <span class="string"><span class="delimiter">'</span><span class="content">players[guitar]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Steve Hackett</span><span class="delimiter">'</span></span>],
                  <span class="string"><span class="delimiter">'</span><span class="content">players[vocals]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Peter Gabriel</span><span class="delimiter">'</span></span>],
                  <span class="string"><span class="delimiter">'</span><span class="content">players[keyboards]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Tony Banks</span><span class="delimiter">'</span></span>]]

<span class="keyword">def</span> album = <span class="keyword">new</span> Album(bindingMap)

<span class="keyword">assert</span> album.title == <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.size() == <span class="integer">3</span>
<span class="keyword">assert</span> album.players.guitar.name == <span class="string"><span class="delimiter">'</span><span class="content">Steve Hackett</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.vocals.name == <span class="string"><span class="delimiter">'</span><span class="content">Peter Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.keyboards.name == <span class="string"><span class="delimiter">'</span><span class="content">Tony Banks</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>When updating an existing <code>Map</code>, if the key specified in the binding <code>Map</code> does not exist in the <code>Map</code> being bound to then a new value will be created and added to the <code>Map</code> with the specified key as in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>,
                  <span class="string"><span class="delimiter">'</span><span class="content">players[guitar]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Steve Hackett</span><span class="delimiter">'</span></span>],
                  <span class="string"><span class="delimiter">'</span><span class="content">players[vocals]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Peter Gabriel</span><span class="delimiter">'</span></span>],
                  <span class="string"><span class="delimiter">'</span><span class="content">players[keyboards]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Tony Banks</span><span class="delimiter">'</span></span>]]

<span class="keyword">def</span> album = <span class="keyword">new</span> Album(bindingMap)

<span class="keyword">assert</span> album.title == <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.size() == <span class="integer">3</span>
<span class="keyword">assert</span> album.players.guitar.name == <span class="string"><span class="delimiter">'</span><span class="content">Steve Hackett</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.vocals.name  == <span class="string"><span class="delimiter">'</span><span class="content">Peter Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.keyboards.name  == <span class="string"><span class="delimiter">'</span><span class="content">Tony Banks</span><span class="delimiter">'</span></span>

<span class="keyword">def</span> updatedBindingMap = [<span class="string"><span class="delimiter">'</span><span class="content">players[drums]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Phil Collins</span><span class="delimiter">'</span></span>],
                         <span class="string"><span class="delimiter">'</span><span class="content">players[keyboards]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Anthony George Banks</span><span class="delimiter">'</span></span>]]

album.properties = updatedBindingMap

<span class="keyword">assert</span> album.title == <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.size() == <span class="integer">4</span>
<span class="keyword">assert</span> album.players.guitar.name == <span class="string"><span class="delimiter">'</span><span class="content">Steve Hackett</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.vocals.name == <span class="string"><span class="delimiter">'</span><span class="content">Peter Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.keyboards.name == <span class="string"><span class="delimiter">'</span><span class="content">Anthony George Banks</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.drums.name == <span class="string"><span class="delimiter">'</span><span class="content">Phil Collins</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_binding_request_data_to_the_model">Binding Request Data to the Model</h4>
<div class="paragraph">
<p>The <a href="../ref/Controllers/params.html">params</a> object that is available in a controller has special behavior that helps convert dotted request parameter names into nested Maps that the data binder can work with.  For example, if a request includes request parameters named <code>person.homeAddress.country</code> and <code>person.homeAddress.city</code> with values 'USA' and 'St. Louis' respectively, <code>params</code> would include entries like these:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">[<span class="key">person</span>: [<span class="key">homeAddress</span>: [<span class="key">country</span>: <span class="string"><span class="delimiter">'</span><span class="content">USA</span><span class="delimiter">'</span></span>, <span class="key">city</span>: <span class="string"><span class="delimiter">'</span><span class="content">St. Louis</span><span class="delimiter">'</span></span>]]]</code></pre>
</div>
</div>
<div class="paragraph">
<p>There are two ways to bind request parameters onto the properties of a domain class. The first involves using a domain classes' Map constructor:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">save</span>() {
    <span class="keyword">def</span> b = <span class="keyword">new</span> <span class="predefined-type">Book</span>(params)
    b.save()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The data binding happens within the code <code>new Book(params)</code>. By passing the <a href="../ref/Controllers/params.html">params</a> object to the domain class constructor Grails automatically recognizes that you are trying to bind from request parameters. So if we had an incoming request like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/book/save?title=The%20Stand&amp;author=Stephen%20King</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then the <code>title</code> and <code>author</code> request parameters would automatically be set on the domain class. You can use the <a href="../ref/Domain%20Classes/properties.html">properties</a> property to perform data binding onto an existing instance:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">save</span>() {
    <span class="keyword">def</span> b = <span class="predefined-type">Book</span>.get(params.id)
    b.properties = params
    b.save()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This has the same effect as using the implicit constructor.</p>
</div>
<div class="paragraph">
<p>When binding an empty String (a String with no characters in it, not even spaces), the data binder will convert the empty String to null.  This simplifies the most common case where the intent is to treat an empty form field as having the value null since there isn&#8217;t a way to actually submit a null as a request parameter.  When this behavior is not desirable the application may assign the value directly.</p>
</div>
<div class="paragraph">
<p>The mass property binding mechanism will by default automatically trim all Strings at binding time.  To disable this behavior set the <code>grails.databinding.trimStrings</code> property to false in <code>grails-app/conf/application.groovy</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// the default value is true</span>
grails.databinding.trimStrings = <span class="predefined-constant">false</span>

<span class="comment">// ...</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The mass property binding mechanism will by default automatically convert all empty Strings to null at binding time.  To disable this behavior set the <code>grails.databinding.convertEmptyStringsToNull</code> property to false in <code>grails-app/conf/application.groovy</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// the default value is true</span>
grails.databinding.convertEmptyStringsToNull = <span class="predefined-constant">false</span>

<span class="comment">// ...</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The order of events is that the String trimming happens and then null conversion happens so if <code>trimStrings</code> is <code>true</code> and <code>convertEmptyStringsToNull</code> is <code>true</code>, not only will empty Strings be converted to null but also blank Strings.  A blank String is any String such that the <code>trim()</code> method returns an empty String.</p>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
These forms of data binding in Grails are very convenient, but also indiscriminate. In other words, they will bind <em>all</em> non-transient, typed instance properties of the target object, including ones that you may not want bound. Just because the form in your UI doesn&#8217;t submit all the properties, an attacker can still send malign data via a raw HTTP request. Fortunately, Grails also makes it easy to protect against such attacks - see the section titled "Data Binding and Security concerns" for more information.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_and_single_ended_associations">Data binding and Single-ended Associations</h4>
<div class="paragraph">
<p>If you have a <code>one-to-one</code> or <code>many-to-one</code> association you can use Grails' data binding capability to update these relationships too. For example if you have an incoming request such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/book/save?author.id=20</code></pre>
</div>
</div>
<div class="paragraph">
<p>Grails will automatically detect the <code>.id</code> suffix on the request parameter and look up the <code>Author</code> instance for the given id when doing data binding such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> b = <span class="keyword">new</span> <span class="predefined-type">Book</span>(params)</code></pre>
</div>
</div>
<div class="paragraph">
<p>An association property can be set to <code>null</code> by passing the literal <code>String</code> "null". For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/book/save?author.id=null</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_and_many_ended_associations">Data Binding and Many-ended Associations</h4>
<div class="paragraph">
<p>If you have a one-to-many or many-to-many association there are different techniques for data binding depending of the association type.</p>
</div>
<div class="paragraph">
<p>If you have a <code>Set</code> based association (the default for a <code>hasMany</code>) then the simplest way to populate an association is to send a list of identifiers. For example consider the usage of <code>&lt;g:select&gt;</code> below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${Book.list()}</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">size</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">5</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">multiple</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">yes</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">optionKey</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">id</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${author?.books}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>This produces a select box that lets you select multiple values. In this case if you submit the form Grails will automatically use the identifiers from the select box to populate the <code>books</code> association.</p>
</div>
<div class="paragraph">
<p>However, if you have a scenario where you want to update the properties of the associated objects the this technique won&#8217;t work. Instead you use the subscript operator:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:textField</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">the Stand</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;g:textField</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[1].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">the Shining</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>However, with <code>Set</code> based association it is critical that you render the mark-up in the same order that you plan to do the update in. This is because a <code>Set</code> has no concept of order, so although we&#8217;re referring to <code>books[0]</code> and <code>books[1]</code> it is not guaranteed that the order of the association will be correct on the server side unless you apply some explicit sorting yourself.</p>
</div>
<div class="paragraph">
<p>This is not a problem if you use <code>List</code> based associations, since a <code>List</code> has a defined order and an index you can refer to. This is also true of <code>Map</code> based associations.</p>
</div>
<div class="paragraph">
<p>Note also that if the association you are binding to has a size of two and you refer to an element that is outside the size of association:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:textField</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">the Stand</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;g:textField</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[1].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">the Shining</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;g:textField</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[2].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">Red Madder</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Then Grails will automatically create a new instance for you at the defined position.</p>
</div>
<div class="paragraph">
<p>You can bind existing instances of the associated type to a <code>List</code> using the same <code>.id</code> syntax as you would use with a single-ended association. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].id</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${bookList}</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${author?.books[0]?.id}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>

<span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[1].id</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${bookList}</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${author?.books[1]?.id}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>

<span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[2].id</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${bookList}</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${author?.books[2]?.id}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Would allow individual entries in the <code>books List</code> to be selected separately.</p>
</div>
<div class="paragraph">
<p>Entries at particular indexes can be removed in the same way too. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].id</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${Book.list()}</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${author?.books[0]?.id}</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">noSelection</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">['null': '']</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Will render a select box that will remove the association at <code>books[0]</code> if the empty option is chosen.</p>
</div>
<div class="paragraph">
<p>Binding to a <code>Map</code> property works the same way except that the list index in the parameter name is replaced by the map key:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">images[cover].id</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${Image.list()}</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${book?.images[cover]?.id}</span><span class="delimiter">&quot;</span></span>
          <span class="attribute-name">noSelection</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">['null': '']</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>This would bind the selected image into the <code>Map</code> property <code>images</code> under a key of <code>"cover"</code>.</p>
</div>
<div class="paragraph">
<p>When binding to Maps, Arrays and Collections the data binder will automatically grow the size of the collections as necessary.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The default limit to how large the binder will grow a collection is 256. If the data binder encounters an entry that requires the collection be grown beyond that limit, the entry is ignored.  The limit may be configured by assigning a value to the <code>grails.databinding.autoGrowCollectionLimit</code> property in <code>application.groovy</code>.
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// the default value is 256</span>
grails.databinding.autoGrowCollectionLimit = <span class="integer">128</span>

<span class="comment">// ...</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_with_multiple_domain_classes">Data binding with Multiple domain classes</h4>
<div class="paragraph">
<p>It is possible to bind data to multiple domain objects from the <a href="../ref/Controllers/params.html">params</a> object.</p>
</div>
<div class="paragraph">
<p>For example so you have an incoming request to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">/book/save?book.title=The%20Stand&amp;author.name=Stephen%20King</code></pre>
</div>
</div>
<div class="paragraph">
<p>You&#8217;ll notice the difference with the above request is that each parameter has a prefix such as <code>author.</code> or <code>book.</code> which is used to isolate which parameters belong to which type. Grails' <code>params</code> object is like a multi-dimensional hash and you can index into it to isolate only a subset of the parameters to bind.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> b = <span class="keyword">new</span> <span class="predefined-type">Book</span>(params.book)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice how we use the prefix before the first dot of the <code>book.title</code> parameter to isolate only parameters below this level to bind. We could do the same with an <code>Author</code> domain class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> a = <span class="keyword">new</span> Author(params.author)</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_and_action_arguments">Data Binding and Action Arguments</h4>
<div class="paragraph">
<p>Controller action arguments are subject to request parameter data binding.  There are 2 categories of controller action arguments.  The first category is command objects.  Complex types are treated as command objects.  See the <a href="theWebLayer.html#commandObjects">Command Objects</a> section of the user guide for details.  The other category is basic object types.  Supported types are the 8 primitives, their corresponding type wrappers and <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html">java.lang.String</a>.  The default behavior is to map request parameters to action arguments by name:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AccountingController</span> {

   <span class="comment">// accountNumber will be initialized with the value of params.accountNumber</span>
   <span class="comment">// accountType will be initialized with params.accountType</span>
   <span class="keyword">def</span> <span class="function">displayInvoice</span>(<span class="predefined-type">String</span> accountNumber, <span class="type">int</span> accountType) {
       <span class="comment">// ...</span>
   }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>For primitive arguments and arguments which are instances of any of the primitive type wrapper classes a type conversion has to be carried out before the request parameter value can be bound to the action argument.  The type conversion happens automatically.  In a case like the example shown above, the <code>params.accountType</code> request parameter has to be converted to an <code>int</code>.  If type conversion fails for any reason, the argument will have its default value per normal Java behavior (null for type wrapper references, false for booleans and zero for numbers) and a corresponding error will be added to the <code>errors</code> property of the defining controller.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">/accounting/displayInvoice?accountNumber=B59786&amp;accountType=bogusValue</code></pre>
</div>
</div>
<div class="paragraph">
<p>Since "bogusValue" cannot be converted to type int, the value of accountType will be zero, the controller&#8217;s <code>errors.hasErrors()</code> will be true, the controller&#8217;s <code>errors.errorCount</code> will be equal to 1 and the controller&#8217;s <code>errors.getFieldError('accountType')</code> will contain the corresponding error.</p>
</div>
<div class="paragraph">
<p>If the argument name does not match the name of the request parameter then the <code>@grails.web.RequestParameter</code> annotation may be applied to an argument to express the name of the request parameter which should be bound to that argument:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.web.RequestParameter</span>

<span class="type">class</span> <span class="class">AccountingController</span> {

   <span class="comment">// mainAccountNumber will be initialized with the value of params.accountNumber</span>
   <span class="comment">// accountType will be initialized with params.accountType</span>
   <span class="keyword">def</span> <span class="function">displayInvoice</span>(<span class="annotation">@RequestParameter</span>(<span class="string"><span class="delimiter">'</span><span class="content">accountNumber</span><span class="delimiter">'</span></span>) <span class="predefined-type">String</span> mainAccountNumber, <span class="type">int</span> accountType) {
       <span class="comment">// ...</span>
   }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_and_type_conversion_errors">Data binding and type conversion errors</h4>
<div class="paragraph">
<p>Sometimes when performing data binding it is not possible to convert a particular String into a particular target type. This results in a type conversion error. Grails will retain type conversion errors inside the <a href="../ref/Domain%20Classes/errors.html">errors</a> property of a Grails domain class. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Book</span> {
    ...
    URL publisherURL
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here we have a domain class <code>Book</code> that uses the <code>java.net.URL</code> class to represent URLs. Given an incoming request such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">/book/save?publisherURL=a-bad-url</code></pre>
</div>
</div>
<div class="paragraph">
<p>it is not possible to bind the string <code>a-bad-url</code> to the <code>publisherURL</code> property as a type mismatch error occurs. You can check for these like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> b = <span class="keyword">new</span> <span class="predefined-type">Book</span>(params)

<span class="keyword">if</span> (b.hasErrors()) {
    println <span class="string"><span class="delimiter">&quot;</span><span class="content">The value </span><span class="inline"><span class="inline-delimiter">${</span>b.errors.getFieldError(<span class="string"><span class="delimiter">'</span><span class="content">publisherURL</span><span class="delimiter">'</span></span>).rejectedValue<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span> +
            <span class="string"><span class="delimiter">&quot;</span><span class="content"> is not a valid URL!</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Although we have not yet covered error codes (for more information see the section on <a href="validation.html">validation</a>), for type conversion errors you would want a message from the <code>grails-app/i18n/messages.properties</code> file to use for the error. You can use a generic error message handler such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">typeMismatch.java.net.URL=The field {<span class="integer">0</span>} is not a valid <span class="predefined-type">URL</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Or a more specific one:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">typeMismatch.Book.publisherURL=The publisher <span class="predefined-type">URL</span> you specified is not a valid <span class="predefined-type">URL</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_the_bindusing_annotation">The BindUsing Annotation</h4>
<div class="paragraph">
<p>The <a href="http://docs.grails.org/3.2.11/api/grails/databinding/BindUsing.html">BindUsing</a> annotation may be used to define a custom binding mechanism for a particular field in a class.  Any time data binding is being applied to the field the closure value of the annotation will be invoked with 2 arguments.  The first argument is the object that data binding is being applied to and the second argument is <a href="http://docs.grails.org/3.2.11/api/grails/databinding/DataBindingSource.html">DataBindingSource</a> which is the data source for the data binding.  The value returned from the closure will be bound to the property.  The following example would result in the upper case version of the <code>name</code> value in the source being applied to the <code>name</code> field during data binding.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.databinding.BindUsing</span>

<span class="type">class</span> <span class="class">SomeClass</span> {
    <span class="annotation">@BindUsing</span>({obj, source -&gt;

        <span class="comment">//source is DataSourceBinding which is similar to a Map</span>
        <span class="comment">//and defines getAt operation but source.name cannot be used here.</span>
        <span class="comment">//In order to get name from source use getAt instead as shown below.</span>

        source[<span class="string"><span class="delimiter">'</span><span class="content">name</span><span class="delimiter">'</span></span>]?.toUpperCase()
    })
    <span class="predefined-type">String</span> name
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Note that data binding is only possible when the name of the request parameter matches with the field name in the class.
Here, <code>name</code> from request parameters matches with <code>name</code> from <code>SomeClass</code>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The <a href="http://docs.grails.org/3.2.11/api/grails/databinding/BindUsing.html">BindUsing</a> annotation may be used to define a custom binding mechanism for all of the fields on a particular class. When the annotation is applied to a class, the value assigned to the annotation should be a class which implements the <a href="http://docs.grails.org/3.2.11/api/grails/databinding/BindingHelper.html">BindingHelper</a> interface.  An instance of that class will be used any time a value is bound to a property in the class that this annotation has been applied to.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@BindUsing</span>(SomeClassWhichImplementsBindingHelper)
<span class="type">class</span> <span class="class">SomeClass</span> {
    <span class="predefined-type">String</span> someProperty
    <span class="predefined-type">Integer</span> someOtherProperty
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_custom_data_converters">Custom Data Converters</h4>
<div class="paragraph">
<p>The binder will do a lot of type conversion automatically.  Some applications may want to define their own mechanism for converting values and a simple way to do this is to write a class which implements <a href="http://docs.grails.org/3.2.11/api/grails/databinding/converters/ValueConverter.html">ValueConverter</a> and register an instance of that class as a bean in the Spring application context.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.myapp.converters

<span class="keyword">import</span> <span class="include">grails.databinding.converters.ValueConverter</span>

<span class="comment">/**
 * A custom converter which will convert String of the
 * form 'city:state' into an Address object.
 */</span>
<span class="type">class</span> <span class="class">AddressValueConverter</span> <span class="directive">implements</span> ValueConverter {

    <span class="type">boolean</span> canConvert(value) {
        value <span class="keyword">instanceof</span> <span class="predefined-type">String</span>
    }

    <span class="keyword">def</span> <span class="function">convert</span>(value) {
        <span class="keyword">def</span> pieces = value.split(<span class="string"><span class="delimiter">'</span><span class="content">:</span><span class="delimiter">'</span></span>)
        <span class="keyword">new</span> com.myapp.Address(<span class="key">city</span>: pieces[<span class="integer">0</span>], <span class="key">state</span>: pieces[<span class="integer">1</span>])
    }

    <span class="predefined-type">Class</span>&lt;?&gt; getTargetType() {
        com.myapp.Address
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>An instance of that class needs to be registered as a bean in the Spring application context.  The bean name is not important.  All beans that implemented ValueConverter will be automatically plugged in to the data binding process.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/spring/resources.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
    addressConverter com.myapp.converters.AddressValueConverter
    <span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Person</span> {
    <span class="predefined-type">String</span> firstName
    Address homeAddress
}

<span class="type">class</span> <span class="class">Address</span> {
    <span class="predefined-type">String</span> city
    <span class="predefined-type">String</span> state
}

<span class="keyword">def</span> person = <span class="keyword">new</span> Person()
person.properties = [<span class="key">firstName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Jeff</span><span class="delimiter">'</span></span>, <span class="key">homeAddress</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">O'Fallon:Missouri</span><span class="delimiter">&quot;</span></span>]
<span class="keyword">assert</span> person.firstName == <span class="string"><span class="delimiter">'</span><span class="content">Jeff</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.homeAddress.city = <span class="string"><span class="delimiter">&quot;</span><span class="content">O'Fallon</span><span class="delimiter">&quot;</span></span>
<span class="keyword">assert</span> person.homeAddress.state = <span class="string"><span class="delimiter">'</span><span class="content">Missouri</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_date_formats_for_data_binding">Date Formats For Data Binding</h4>
<div class="paragraph">
<p>A custom date format may be specified to be used when binding a String to a Date value by applying the <a href="http://docs.grails.org/3.2.11/api/grails/databinding/BindingFormat.html">BindingFormat</a> annotation to a Date field.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.databinding.BindingFormat</span>

<span class="type">class</span> <span class="class">Person</span> {
    <span class="annotation">@BindingFormat</span>(<span class="string"><span class="delimiter">'</span><span class="content">MMddyyyy</span><span class="delimiter">'</span></span>)
    <span class="predefined-type">Date</span> birthDate
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>A global setting may be configured in <code>application.groovy</code> to define date formats which will be used application wide when binding to Date.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.databinding.dateFormats = [<span class="string"><span class="delimiter">'</span><span class="content">MMddyyyy</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">yyyy-MM-dd HH:mm:ss.S</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">yyyy-MM-dd'T'hh:mm:ss'Z'</span><span class="delimiter">&quot;</span></span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The formats specified in <code>grails.databinding.dateFormats</code> will be attempted in the order in which they are included in the List.  If a property is marked with <code>@BindingFormat</code>, the <code>@BindingFormat</code> will take precedence over the values specified in <code>grails.databinding.dateFormats</code>.</p>
</div>
<div class="paragraph">
<p>The formats configured by default are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>yyyy-MM-dd HH:mm:ss.S</code></p>
</li>
<li>
<p><code>yyyy-MM-dd&#8217;T&#8217;hh:mm:ss&#8217;Z'</code></p>
</li>
<li>
<p><code>yyyy-MM-dd HH:mm:ss.S z</code></p>
</li>
<li>
<p><code>yyyy-MM-dd&#8217;T&#8217;HH:mm:ss.SSSX</code></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_custom_formatted_converters">Custom Formatted Converters</h4>
<div class="paragraph">
<p>You may supply your own handler for the <a href="http://docs.grails.org/3.2.11/api/grails/databinding/BindingFormat.html">BindingFormat</a> annotation by writing a class which implements the <a href="http://docs.grails.org/3.2.11/api/grails/databinding/converters/FormattedValueConverter.html">FormattedValueConverter</a> interface and registering an instance of that class as a bean in the Spring application context.  Below is an example of a trivial custom String formatter that might convert the case of a String based on the value assigned to the BindingFormat annotation.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.myapp.converters

<span class="keyword">import</span> <span class="include">grails.databinding.converters.FormattedValueConverter</span>

<span class="type">class</span> <span class="class">FormattedStringValueConverter</span> <span class="directive">implements</span> FormattedValueConverter {
    <span class="keyword">def</span> <span class="function">convert</span>(value, <span class="predefined-type">String</span> format) {
        <span class="keyword">if</span>(<span class="string"><span class="delimiter">'</span><span class="content">UPPERCASE</span><span class="delimiter">'</span></span> == format) {
            value = value.toUpperCase()
        } <span class="keyword">else</span> <span class="keyword">if</span>(<span class="string"><span class="delimiter">'</span><span class="content">LOWERCASE</span><span class="delimiter">'</span></span> == format) {
            value = value.toLowerCase()
        }
        value
    }

    <span class="predefined-type">Class</span> getTargetType() {
        <span class="comment">// specifies the type to which this converter may be applied</span>
        <span class="predefined-type">String</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>An instance of that class needs to be registered as a bean in the Spring application context.  The bean name is not important.  All beans that implemented FormattedValueConverter will be automatically plugged in to the data binding process.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/spring/resources.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
    formattedStringConverter com.myapp.converters.FormattedStringValueConverter
    <span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With that in place the <code>BindingFormat</code> annotation may be applied to String fields to inform the data binder to take advantage of the custom converter.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.databinding.BindingFormat</span>

<span class="type">class</span> <span class="class">Person</span> {
    <span class="annotation">@BindingFormat</span>(<span class="string"><span class="delimiter">'</span><span class="content">UPPERCASE</span><span class="delimiter">'</span></span>)
    <span class="predefined-type">String</span> someUpperCaseString

    <span class="annotation">@BindingFormat</span>(<span class="string"><span class="delimiter">'</span><span class="content">LOWERCASE</span><span class="delimiter">'</span></span>)
    <span class="predefined-type">String</span> someLowerCaseString

    <span class="predefined-type">String</span> someOtherString
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_localized_binding_formats">Localized Binding Formats</h4>
<div class="paragraph">
<p>The <code>BindingFormat</code> annotation supports localized format strings by using the optional <code>code</code> attribute.  If a value is assigned to the code attribute that value will be used as the message code to retrieve the binding format string from the <code>messageSource</code> bean in the Spring application context and that lookup will be localized.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.databinding.BindingFormat</span>

<span class="type">class</span> <span class="class">Person</span> {
    <span class="annotation">@BindingFormat</span>(code=<span class="string"><span class="delimiter">'</span><span class="content">date.formats.birthdays</span><span class="delimiter">'</span></span>)
    <span class="predefined-type">Date</span> birthDate
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">#</span> grails-app/conf/i18n/messages.properties
date.formats.birthdays=MMddyyyy</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">#</span> grails-app/conf/i18n/messages_es.properties
date.formats.birthdays=ddMMyyyy</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_structured_data_binding_editors">Structured Data Binding Editors</h4>
<div class="paragraph">
<p>A structured data binding editor is a helper class which can bind structured request parameters to a property.  The common use case for structured binding is binding to a <code>Date</code> object which might be constructed from several smaller pieces of information contained in several request parameters with names like <code>birthday_month</code>, <code>birthday_date</code> and <code>birthday_year</code>.  The structured editor would retrieve all of those individual pieces of information and use them to construct a <code>Date</code>.</p>
</div>
<div class="paragraph">
<p>The framework provides a structured editor for binding to <code>Date</code> objects.  An application may register its own structured editors for whatever types are appropriate.  Consider the following classes:</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/databinding/Gadget.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> databinding

<span class="type">class</span> <span class="class">Gadget</span> {
    <span class="predefined-type">Shape</span> expandedShape
    <span class="predefined-type">Shape</span> compressedShape
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/databinding/Shape.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> databinding

<span class="type">class</span> <span class="class">Shape</span> {
    <span class="type">int</span> area
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>A <code>Gadget</code> has 2 <code>Shape</code> fields.  A <code>Shape</code> has an <code>area</code> property.  It may be that the application wants to accept request parameters like <code>width</code> and <code>height</code> and use those to calculate the <code>area</code> of a <code>Shape</code> at binding time.  A structured binding editor is well suited for that.</p>
</div>
<div class="paragraph">
<p>The way to register a structured editor with the data binding process is to add an instance of the <a href="http://docs.grails.org/3.2.11/api/grails/databinding/TypedStructuredBindingEditor.html">grails.databinding.TypedStructuredBindingEditor</a> interface to the Spring application context.  The easiest way to implement the <code>TypedStructuredBindingEditor</code> interface is to extend the <a href="http://docs.grails.org/3.2.11/api/org/grails/databinding/converters/AbstractStructuredDateBindingEditor.html">org.grails.databinding.converters.AbstractStructuredBindingEditor</a> abstract class and override the <code>getPropertyValue</code> method as shown below:</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/databinding/converters/StructuredShapeEditor.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> databinding.converters

<span class="keyword">import</span> <span class="include">databinding.Shape</span>

<span class="keyword">import</span> <span class="include">org.grails.databinding.converters.AbstractStructuredBindingEditor</span>

<span class="type">class</span> <span class="class">StructuredShapeEditor</span> <span class="directive">extends</span> AbstractStructuredBindingEditor&lt;<span class="predefined-type">Shape</span>&gt; {

    <span class="directive">public</span> <span class="predefined-type">Shape</span> getPropertyValue(<span class="predefined-type">Map</span> values) {
        <span class="comment">// retrieve the individual values from the Map</span>
        <span class="keyword">def</span> width = values.width <span class="keyword">as</span> <span class="type">int</span>
        <span class="keyword">def</span> height = values.height <span class="keyword">as</span> <span class="type">int</span>

        <span class="comment">// use the values to calculate the area of the Shape</span>
        <span class="keyword">def</span> area = width * height

        <span class="comment">// create and return a Shape with the appropriate area</span>
        <span class="keyword">new</span> <span class="predefined-type">Shape</span>(<span class="key">area</span>: area)
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>An instance of that class needs to be registered with the Spring application context:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/spring/resources.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
    shapeEditor databinding.converters.StructuredShapeEditor
    <span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When the data binder binds to an instance of the <code>Gadget</code> class it will check to see if there are request parameters with names <code>compressedShape</code> and <code>expandedShape</code> which have a value of "struct" and if they do exist, that will trigger the use of the <code>StructuredShapeEditor</code>.  The individual components of the structure need to have parameter names of the form propertyName_structuredElementName.  In the case of the <code>Gadget</code> class above that would mean that the <code>compressedShape</code> request parameter should have a value of "struct" and the <code>compressedShape_width</code> and <code>compressedShape_height</code> parameters should have values which represent the width and the height of the compressed <code>Shape</code>.  Similarly, the <code>expandedShape</code> request parameter should have a value of "struct" and the <code>expandedShape_width</code> and <code>expandedShape_height</code> parameters should have values which represent the width and the height of the expanded <code>Shape</code>.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/demo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">DemoController</span> {

    <span class="keyword">def</span> <span class="function">createGadget</span>(Gadget gadget) {
        <span class="comment">/*
        /demo/createGadget?expandedShape=struct&amp;expandedShape_width=80&amp;expandedShape_height=30
                          &amp;compressedShape=struct&amp;compressedShape_width=10&amp;compressedShape_height=3

        */</span>

        <span class="comment">// with the request parameters shown above gadget.expandedShape.area would be 2400</span>
        <span class="comment">// and gadget.compressedShape.area would be 30</span>
        <span class="comment">// ...</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Typically the request parameters with "struct" as their value would be represented by hidden form fields.</p>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_event_listeners">Data Binding Event Listeners</h4>
<div class="paragraph">
<p>The <a href="http://docs.grails.org/3.2.11/api/grails/databinding/events/DataBindingListener.html">DataBindingListener</a> interface provides a mechanism for listeners to be notified of data binding events.  The interface looks like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> grails.databinding.events;

<span class="keyword">import</span> <span class="include">grails.databinding.errors.BindingError</span>;

<span class="comment">/**
 * A listener which will be notified of events generated during data binding.
 *
 * @author Jeff Brown
 * @since 3.0
 * @see DataBindingListenerAdapter
 */</span>
<span class="directive">public</span> <span class="type">interface</span> DataBindingListener {

    <span class="comment">/**
     * @return true if the listener is interested in events for the specified type.
     */</span>
    <span class="type">boolean</span> supports(<span class="predefined-type">Class</span>&lt;?&gt; clazz);

    <span class="comment">/**
     * Called when data binding is about to start.
     *
     * @param target The object data binding is being imposed upon
     * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
     * @return true if data binding should continue
     */</span>
    <span class="predefined-type">Boolean</span> beforeBinding(<span class="predefined-type">Object</span> target, <span class="predefined-type">Object</span> errors);

    <span class="comment">/**
     * Called when data binding is about to imposed on a property
     *
     * @param target The object data binding is being imposed upon
     * @param propertyName The name of the property being bound to
     * @param value The value of the property being bound
     * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
     * @return true if data binding should continue, otherwise return false
     */</span>
    <span class="predefined-type">Boolean</span> beforeBinding(<span class="predefined-type">Object</span> target, <span class="predefined-type">String</span> propertyName, <span class="predefined-type">Object</span> value, <span class="predefined-type">Object</span> errors);

    <span class="comment">/**
     * Called after data binding has been imposed on a property
     *
     * @param target The object data binding is being imposed upon
     * @param propertyName The name of the property that was bound to
     * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
     */</span>
    <span class="type">void</span> afterBinding(<span class="predefined-type">Object</span> target, <span class="predefined-type">String</span> propertyName, <span class="predefined-type">Object</span> errors);

    <span class="comment">/**
     * Called after data binding has finished.
     *
     * @param target The object data binding is being imposed upon
     * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
     */</span>
    <span class="type">void</span> afterBinding(<span class="predefined-type">Object</span> target, <span class="predefined-type">Object</span> errors);

    <span class="comment">/**
     * Called when an error occurs binding to a property
     * @param error encapsulates information about the binding error
     * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
     * @see BindingError
     */</span>
    <span class="type">void</span> bindingError(BindingError error, <span class="predefined-type">Object</span> errors);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Any bean in the Spring application context which implements that interface will automatically be registered with the data binder.  The <a href="http://docs.grails.org/3.2.11/api/grails/databinding/events/DataBindingListenerAdapter.html">DataBindingListenerAdapter</a> class implements the <code>DataBindingListener</code> interface and provides default implementations for all of the methods in the interface so this class is well suited for subclassing so your listener class only needs to provide implementations for the methods your listener is interested in.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_the_data_binder_directly">Using The Data Binder Directly</h4>
<div class="paragraph">
<p>There are situations where an application may want to use the data binder directly.  For example, to do binding in a Service on some arbitrary object which is not a domain class.  The following will not work because the <code>properties</code> property is read only.</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/bindingdemo/Widget.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> bindingdemo

<span class="type">class</span> <span class="class">Widget</span> {
    <span class="predefined-type">String</span> name
    <span class="predefined-type">Integer</span> size
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">grails-app/services/bindingdemo/WidgetService.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> bindingdemo

<span class="type">class</span> <span class="class">WidgetService</span> {

    <span class="keyword">def</span> <span class="function">updateWidget</span>(Widget widget, <span class="predefined-type">Map</span> data) {
        <span class="comment">// this will throw an exception because</span>
        <span class="comment">// properties is read-only</span>
        widget.properties = data
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>An instance of the data binder is in the Spring application context with a bean name of <code>grailsWebDataBinder</code>.  That bean implements the <a href="http://docs.grails.org/3.2.11/api/grails/databinding/DataBinder.html">DataBinder</a> interface.  The following code demonstrates using the data binder directly.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/services/bindingdmeo/WidgetService</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> bindingdemo

<span class="keyword">import</span> <span class="include">grails.databinding.SimpleMapDataBindingSource</span>

<span class="type">class</span> <span class="class">WidgetService</span> {

    <span class="comment">// this bean will be autowired into the service</span>
    <span class="keyword">def</span> grailsWebDataBinder

    <span class="keyword">def</span> <span class="function">updateWidget</span>(Widget widget, <span class="predefined-type">Map</span> data) {
        grailsWebDataBinder.bind widget, data <span class="keyword">as</span> SimpleMapDataBindingSource
    }

}</code></pre>
</div>
</div>
<div class="paragraph">
<p>See the <a href="http://docs.grails.org/3.2.11/api/grails/databinding/DataBinder.html">DataBinder</a> documentation for more information about overloaded versions
of the <code>bind</code> method.</p>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_and_security_concerns">Data Binding and Security Concerns</h4>
<div class="paragraph">
<p>When batch updating properties from request parameters you need to be careful not to allow clients to bind malicious data to domain classes and be persisted in the database. You can limit what properties are bound to a given domain class using the subscript operator:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = Person.get(<span class="integer">1</span>)

p.properties[<span class="string"><span class="delimiter">'</span><span class="content">firstName</span><span class="delimiter">'</span></span>,<span class="string"><span class="delimiter">'</span><span class="content">lastName</span><span class="delimiter">'</span></span>] = params</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case only the <code>firstName</code> and <code>lastName</code> properties will be bound.</p>
</div>
<div class="paragraph">
<p>Another way to do this is is to use <a href="theWebLayer.html#commandObjects">Command Objects</a> as the target of data binding instead of domain classes. Alternatively there is also the flexible <a href="../ref/Controllers/bindData.html">bindData</a> method.</p>
</div>
<div class="paragraph">
<p>The <code>bindData</code> method allows the same data binding capability, but to arbitrary objects:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = <span class="keyword">new</span> Person()
bindData(p, params)</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>bindData</code> method also lets you exclude certain parameters that you don&#8217;t want updated:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = <span class="keyword">new</span> Person()
bindData(p, params, [<span class="key">exclude</span>: <span class="string"><span class="delimiter">'</span><span class="content">dateOfBirth</span><span class="delimiter">'</span></span>])</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or include only certain properties:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = <span class="keyword">new</span> Person()
bindData(p, params, [<span class="key">include</span>: [<span class="string"><span class="delimiter">'</span><span class="content">firstName</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">lastName</span><span class="delimiter">'</span></span>]])</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
If an empty List is provided as a value for the <code>include</code> parameter then all fields will be subject to binding if they are not explicitly excluded.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The <a href="../ref/Constraints/bindable.html">bindable</a> constraint can be used to globally prevent data binding for certain properties.</p>
</div>
</div>


<h2 id="jsonResponses">8.1.6 Responding with JSON</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/jsonResponses.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_using_the_respond_method_to_output_json">Using the respond method to output JSON</h4>
<div class="paragraph">
<p>The <code>respond</code> method is the preferred way to return JSON and integrates with <a href="theWebLayer.html#contentNegotiation">Content Negotiation</a> and <a href="webServices.html#jsonViews">JSON Views</a>.</p>
</div>
<div class="paragraph">
<p>The <code>respond</code> method provides content negotiation strategies to intelligently produce an appropriate response for the given client.</p>
</div>
<div class="paragraph">
<p>For example given the following controller and action:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/example/BookController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> example

<span class="type">class</span> <span class="class">BookController</span> {
    <span class="keyword">def</span> <span class="function">index</span>() {
        respond <span class="predefined-type">Book</span>.list()
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>respond</code> method will take the followings steps:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>If the client <code>Accept</code> header specifies a media type (for example <code>application/json</code>) use that</p>
</li>
<li>
<p>If the file extension of the URI (for example <code>/books.json</code>) includes a format defined in the <code>grails.mime.types</code> property of <code>grails-app/conf/application.yml</code> use the media type defined in the configuration</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>The <code>respond</code> method will then look for an appriopriate <a href="http://docs.grails.org/3.2.11/api/grails/rest/render/Renderer.html">Renderer</a> for the object and the calculated media type from the <a href="http://docs.grails.org/3.2.11/api/grails/rest/render/RendererRegistry.html">RendererRegistry</a>.</p>
</div>
<div class="paragraph">
<p>Grails includes a number of pre-configured <code>Renderer</code> implementations that will produce default representations of JSON responses for the argument passed to <code>respond</code>. For example going to the <code>/book.json</code> URI will produce JSON such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="json">[
    {<span class="error">i</span><span class="error">d</span>:<span class="integer">1</span>,<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>},
    {<span class="error">i</span><span class="error">d</span>:<span class="integer">2</span>,<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Shining</span><span class="delimiter">&quot;</span></span>}
]</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_controlling_the_priority_of_media_types">Controlling the Priority of Media Types</h4>
<div class="paragraph">
<p>By default if you define a controller there is no priority in terms of which format is sent back to the client and Grails assumes you wish to serve HTML as a response type.</p>
</div>
<div class="paragraph">
<p>However if your application is primarily an API, then you can specify the priorty using the <code>responseFormats</code> property:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/example/BookController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> example

<span class="type">class</span> <span class="class">BookController</span> {
    <span class="directive">static</span> responseFormats = [<span class="string"><span class="delimiter">'</span><span class="content">json</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">html</span><span class="delimiter">'</span></span>]
    <span class="keyword">def</span> <span class="function">index</span>() {
        respond <span class="predefined-type">Book</span>.list()
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the above example Grails will respond by default with <code>json</code> if the media type to respond with cannot be calculated from the <code>Accept</code> header or file extension.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_views_to_output_json_responses">Using Views to Output JSON Responses</h4>
<div class="paragraph">
<p>If you define a view (either a GSP or a <a href="webServices.html#jsonViews">JSON View</a>) then Grails will render the view when using the <code>respond</code> method by calculating a model from the argument passed to <code>respond</code>.</p>
</div>
<div class="paragraph">
<p>For example, in the previous listing, if you were to define <code>grails-app/views/index.gson</code> and <code>grails-app/views/index.gsp</code> views, these would be used if the client requested <code>application/json</code> or <code>text/html</code> media types respectively. Thus allowing you to define a single backend capible of serving responses to a web browser or representing your application&#8217;s API.</p>
</div>
<div class="paragraph">
<p>When rendering the view, Grails will calculate a model to pass to the view based on the type of the value passed to the <code>respond</code> method.</p>
</div>
<div class="paragraph">
<p>The following table summarizes this convention:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Example</th>
<th class="tableblock halign-left valign-top">Argument Type</th>
<th class="tableblock halign-left valign-top">Calculated Model Variable</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond Book.list()</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>java.util.List</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>bookList</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond( [] )</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>java.util.List</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>emptyList</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond Book.get(1)</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>example.Book</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>book</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond( [1,2] )</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>java.util.List</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>integerList</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond( [1,2] as Set )</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>java.util.Set</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>integerSet</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond( [1,2] as Integer[] )</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Integer[]</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>integerArray</code></p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>Using this convention you can reference the argument passed to <code>respond</code> from within your view:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/views/book/index.gson</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@Field</span> <span class="predefined-type">List</span>&lt;<span class="predefined-type">Book</span>&gt; bookList = <span class="type">[]</span>

json bookList, { <span class="predefined-type">Book</span> book -&gt;
    title book.title
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You will notice that if <code>Book.list()</code> returns an empty list then the model variable name is translated to <code>emptyList</code>. This is by design and you should provide a default value in the view if no model variable is specified, such as the <code>List</code> in the example above:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/views/book/index.gson</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// defaults to an empty list</span>
<span class="annotation">@Field</span> <span class="predefined-type">List</span>&lt;<span class="predefined-type">Book</span>&gt; bookList = <span class="type">[]</span>
...</code></pre>
</div>
</div>
<div class="paragraph">
<p>There are cases where you may wish to be more explicit and control the name of the model variable. For example if you have a domain inheritance hierarchy where a call to <code>list()</code> my return different child classes relying on automatic calculation may not be reliable.</p>
</div>
<div class="paragraph">
<p>In this case you should pass the model directly using <code>respond</code> and a map argument:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">respond <span class="key">bookList</span>: <span class="predefined-type">Book</span>.list()</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
When responding with any kind of mixed argument types in a collection, always use an explicit model name.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>If you simply wish to augment the calculated model then you can do so by passing a <code>model</code> argument:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">respond <span class="predefined-type">Book</span>.list(), [<span class="key">model</span>: [<span class="key">bookCount</span>: <span class="predefined-type">Book</span>.count()]]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above example will produce a model like <code>[bookList:books, bookCount:totalBooks]</code>, where the calculated model is combined with the model passed in the <code>model</code> argument.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_the_render_method_to_output_json">Using the render method to output JSON</h4>
<div class="paragraph">
<p>The <code>render</code> method can also be used to output JSON, but should only be used for simple cases that don&#8217;t warrant the creation of a JSON view:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">list</span>() {

    <span class="keyword">def</span> results = <span class="predefined-type">Book</span>.list()

    render(<span class="key">contentType</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/json</span><span class="delimiter">&quot;</span></span>) {
        books(results) { <span class="predefined-type">Book</span> b -&gt;
            title b.title
        }
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case the result would be something along the lines of:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="json">[
    {<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>},
    {<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Shining</span><span class="delimiter">&quot;</span></span>}
]</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
This technique for rendering JSON may be ok for very simple responses, but in general you should favour the use of <a href="webServices.html#jsonViews">JSON Views</a> and use the view layer rather than embedding logic in your application.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The same dangers with naming conflicts described above for XML also apply to JSON building.</p>
</div>
</div>

<a name="7.1.8 More on JSONBuilder"><!-- Legacy link --></a>
<h2 id="moreOnJSONBuilder">8.1.7 More on JSONBuilder</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/moreOnJSONBuilder.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>The previous section on XML and JSON responses covered simplistic examples of rendering XML and JSON responses. Whilst the XML builder used by Grails is the standard <a href="http://groovy-lang.org/processing-xml.html#_xmlparser_and_xmlslurper">XmlSlurper</a> found in Groovy.</p>
</div>
<div class="paragraph">
<p>For JSON, since Grails 3.1, Grails uses Groovy&#8217;s <a href="http://docs.groovy-lang.org/latest/html/documentation/core-domain-specific-languages.html#_streamingjsonbuilder">StreamingJsonBuilder</a> by default and you can refer to the <a href="http://docs.groovy-lang.org/latest/html/documentation/core-domain-specific-languages.html#_streamingjsonbuilder">Groovy documentation</a> and <a href="http://docs.groovy-lang.org/latest/html/gapi/groovy/json/StreamingJsonBuilder.html">StreamingJsonBuilder</a> API documentation on how to use it.</p>
</div>


<h2 id="xmlResponses">8.1.8 Responding with XML</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/xmlResponses.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>




<a name="7.1.9 Uploading Files"><!-- Legacy link --></a>
<h2 id="uploadingFiles">8.1.9 Uploading Files</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/uploadingFiles.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_programmatic_file_uploads">Programmatic File Uploads</h4>
<div class="paragraph">
<p>Grails supports file uploads using Spring&#8217;s <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartHttpServletRequest.html">MultipartHttpServletRequest</a> interface. The first step for file uploading is to create a multipart form like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml">Upload Form: <span class="tag">&lt;br</span> <span class="tag">/&gt;</span>
    <span class="tag">&lt;g:uploadForm</span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">upload</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
        <span class="tag">&lt;input</span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">file</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">myFile</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
        <span class="tag">&lt;input</span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">submit</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
    <span class="tag">&lt;/g:uploadForm&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>uploadForm</code> tag conveniently adds the <code>enctype="multipart/form-data"</code> attribute to the standard <code>&lt;g:form&gt;</code> tag.</p>
</div>
<div class="paragraph">
<p>There are then a number of ways to handle the file upload. One is to work with the Spring <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.html">MultipartFile</a> instance directly:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">upload</span>() {
    <span class="keyword">def</span> f = request.getFile(<span class="string"><span class="delimiter">'</span><span class="content">myFile</span><span class="delimiter">'</span></span>)
    <span class="keyword">if</span> (f.empty) {
        flash.message = <span class="string"><span class="delimiter">'</span><span class="content">file cannot be empty</span><span class="delimiter">'</span></span>
        render(<span class="key">view</span>: <span class="string"><span class="delimiter">'</span><span class="content">uploadForm</span><span class="delimiter">'</span></span>)
        <span class="keyword">return</span>
    }

    f.transferTo(<span class="keyword">new</span> <span class="predefined-type">File</span>(<span class="string"><span class="delimiter">'</span><span class="content">/some/local/dir/myfile.txt</span><span class="delimiter">'</span></span>))
    response.sendError(<span class="integer">200</span>, <span class="string"><span class="delimiter">'</span><span class="content">Done</span><span class="delimiter">'</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is convenient for doing transfers to other destinations and manipulating the file directly as you can obtain an <code>InputStream</code> and so on with the <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.html">MultipartFile</a> interface.</p>
</div>
</div>
<div class="sect3">
<h4 id="_file_uploads_through_data_binding">File Uploads through Data Binding</h4>
<div class="paragraph">
<p>File uploads can also be performed using data binding. Consider this <code>Image</code> domain class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Image</span> {
    <span class="type">byte</span><span class="type">[]</span> myFile

    <span class="directive">static</span> constraints = {
        <span class="comment">// Limit upload file size to 2MB</span>
        myFile <span class="key">maxSize</span>: <span class="integer">1024</span> * <span class="integer">1024</span> * <span class="integer">2</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you create an image using the <code>params</code> object in the constructor as in the example below, Grails will automatically bind the file&#8217;s contents as a <code>byte[]</code> to the <code>myFile</code> property:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> img = <span class="keyword">new</span> <span class="predefined-type">Image</span>(params)</code></pre>
</div>
</div>
<div class="paragraph">
<p>It&#8217;s important that you set the <a href="../ref/Constraints/size.html">size</a> or <a href="../ref/Constraints/maxSize.html">maxSize</a> constraints, otherwise your database may be created with a small column size that can&#8217;t handle reasonably sized files. For example, both H2 and MySQL default to a blob size of 255 bytes for <code>byte[]</code> properties.</p>
</div>
<div class="paragraph">
<p>It is also possible to set the contents of the file as a string by changing the type of the <code>myFile</code> property on the image to a String type:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Image</span> {
   <span class="predefined-type">String</span> myFile
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_increase_upload_max_file_size">Increase Upload Max File Size</h4>
<div class="paragraph">
<p>Grails default size for file uploads is 128000 (~128KB). When this limit is exceeded you&#8217;ll see the following exception:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="java">org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase<span class="error">$</span><span class="exception">SizeLimitExceededException</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>You can configure the limit in your <code>application.yml</code> as follows:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yml"><span class="key">grails</span>:
    <span class="key">controllers</span>:
        <span class="key">upload</span>:
            <span class="key">maxFileSize</span>: <span class="string"><span class="content">2000000</span></span>
            <span class="key">maxRequestSize</span>: <span class="string"><span class="content">2000000</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p><code>maxFileSize</code> = The maximum size allowed for uploaded files.</p>
</div>
<div class="paragraph">
<p><code>maxRequestSize</code> =  The maximum size allowed for multipart/form-data requests.</p>
</div>
<div class="paragraph">
<p>You should keep in mind <a href="https://www.owasp.org/index.php/Unrestricted_File_Upload">OWASP recommendations - Unrestricted File Upload</a></p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Limit the file size to a maximum value in order to prevent denial of service attacks.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>These limits exist to prevent DoS attacks and to enforce overall application performance</p>
</div>
</div>

<a name="7.1.10 Command Objects"><!-- Legacy link --></a>
<h2 id="commandObjects">8.1.10 Command Objects</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/commandObjects.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Grails controllers support the concept of command objects. A command object is a class that is used in conjunction with <a href="theWebLayer.html#dataBinding">data binding</a>, usually to allow validation of data that may not fit into an existing domain class.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
A class is only considered to be a command object when it is used as a parameter of an action.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_declaring_command_objects">Declaring Command Objects</h4>
<div class="paragraph">
<p>Command object classes are defined just like any other class.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">LoginCommand</span> <span class="directive">implements</span> grails.validation.Validateable {
    <span class="predefined-type">String</span> username
    <span class="predefined-type">String</span> password

    <span class="directive">static</span> constraints = {
        username(<span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">minSize</span>: <span class="integer">6</span>)
        password(<span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">minSize</span>: <span class="integer">6</span>)
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example, the command object class implements the <code>Validateable</code> trait. The <code>Validateable</code> trait allows the definition of <a href="validation.html#constraints">Constraints</a> just like in <a href="GORM.html">domain classes</a>. If the command object is defined in the same source file as the controller that is using it, Grails will automatically make it <code>Validateable</code>. It is not required that command object classes be validateable.</p>
</div>
<div class="paragraph">
<p>By default, all <code>Validateable</code> object properties which are not instances of <code>java.util.Collection</code> or <code>java.util.Map</code> are <code>nullable: false</code>.  Instances of <code>java.util.Collection</code> and <code>java.util.Map</code> default to <code>nullable: true</code>.  If you want a <code>Validateable</code> that has <code>nullable: true</code> properties by default, you can specify this by defining a <code>defaultNullable</code> method in the class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthorSearchCommand</span> <span class="directive">implements</span> grails.validation.Validateable {
    <span class="predefined-type">String</span>  name
    <span class="predefined-type">Integer</span> age

    <span class="directive">static</span> <span class="type">boolean</span> defaultNullable() {
        <span class="predefined-constant">true</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example, both <code>name</code> and <code>age</code> will allow null values during validation.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_command_objects">Using Command Objects</h4>
<div class="paragraph">
<p>To use command objects, controller actions may optionally specify any number of command object parameters. The parameter types must be supplied so that Grails knows what objects to create and initialize.</p>
</div>
<div class="paragraph">
<p>Before the controller action is executed Grails will automatically create an instance of the command object class and populate its properties by binding the request parameters.  If the command object class is marked with <code>Validateable</code> then the command object will be validated. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">LoginController</span> {

    <span class="keyword">def</span> <span class="function">login</span>(LoginCommand cmd) {
        <span class="keyword">if</span> (cmd.hasErrors()) {
            redirect(<span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">loginForm</span><span class="delimiter">'</span></span>)
            <span class="keyword">return</span>
        }

        <span class="comment">// work with the command object data</span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If the command object&#8217;s type is that of a domain class and there is an <code>id</code> request parameter then instead of invoking the domain class constructor to create a new instance a call will be made to the static <code>get</code> method on the domain class and the value of the <code>id</code> parameter will be passed as an argument.</p>
</div>
<div class="paragraph">
<p>Whatever is returned from that call to <code>get</code> is what will be passed into the controller action.  This means that if there is an <code>id</code> request parameter and no corresponding record is found in the database then the value of the command object will be <code>null</code>.  If an error occurs retrieving the instance from the database then <code>null</code> will be passed as an argument to the controller action and an error will be added the controller&#8217;s <code>errors</code> property.</p>
</div>
<div class="paragraph">
<p>If the command object&#8217;s type is a domain class and there is no <code>id</code> request parameter or there is an <code>id</code> request parameter and its value is empty then <code>null</code> will be passed into the controller action unless the HTTP request method is "POST", in which case a new instance of the domain class will be created by invoking the domain class constructor.  For all of the cases where the domain class instance is non-null, data binding is only performed if the HTTP request method is "POST", "PUT" or "PATCH".</p>
</div>
</div>
<div class="sect3">
<h4 id="_command_objects_and_request_parameter_names">Command Objects And Request Parameter Names</h4>
<div class="paragraph">
<p>Normally request parameter names will be mapped directly to property names in the command object.  Nested parameter names may be used to bind down the object graph in an intuitive way.</p>
</div>
<div class="paragraph">
<p>In the example below a request parameter named <code>name</code> will be bound to the <code>name</code> property of the <code>Person</code> instance and a request parameter named <code>address.city</code> will be bound to the <code>city</code> property of the <code>address</code> property in the <code>Person</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">StoreController</span> {
    <span class="keyword">def</span> <span class="function">buy</span>(Person buyer) {
        <span class="comment">// ...</span>
    }
}

<span class="type">class</span> <span class="class">Person</span> {
    <span class="predefined-type">String</span> name
    Address address
}

<span class="type">class</span> <span class="class">Address</span> {
    <span class="predefined-type">String</span> city
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>A problem may arise if a controller action accepts multiple command objects which happen to contain the same property name.  Consider the following example.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">StoreController</span> {
    <span class="keyword">def</span> <span class="function">buy</span>(Person buyer, Product product) {
        <span class="comment">// ...</span>
    }
}

<span class="type">class</span> <span class="class">Person</span> {
    <span class="predefined-type">String</span> name
    Address address
}

<span class="type">class</span> <span class="class">Address</span> {
    <span class="predefined-type">String</span> city
}

<span class="type">class</span> <span class="class">Product</span> {
    <span class="predefined-type">String</span> name
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If there is a request parameter named <code>name</code> it isn&#8217;t clear if that should represent the name of the <code>Product</code> or the name of the <code>Person</code>.  Another version of the problem can come up if a controller action accepts 2 command objects of the same type as shown below.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">StoreController</span> {
    <span class="keyword">def</span> <span class="function">buy</span>(Person buyer, Person seller, Product product) {
        <span class="comment">// ...</span>
    }
}

<span class="type">class</span> <span class="class">Person</span> {
    <span class="predefined-type">String</span> name
    Address address
}

<span class="type">class</span> <span class="class">Address</span> {
    <span class="predefined-type">String</span> city
}

<span class="type">class</span> <span class="class">Product</span> {
    <span class="predefined-type">String</span> name
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To help deal with this the framework imposes special rules for mapping parameter names to command object types.  The command object data binding will treat all parameters that begin with the controller action parameter name as belonging to the corresponding command object.</p>
</div>
<div class="paragraph">
<p>For example, the <code>product.name</code> request parameter will be bound to the <code>name</code> property in the <code>product</code> argument, the <code>buyer.name</code> request parameter will be bound to the <code>name</code> property in the <code>buyer</code> argument the <code>seller.address.city</code> request parameter will be bound to the <code>city</code> property of the <code>address</code> property of the <code>seller</code> argument, etc&#8230;&#8203;</p>
</div>
</div>
<div class="sect3">
<h4 id="_command_objects_and_dependency_injection">Command Objects and Dependency Injection</h4>
<div class="paragraph">
<p>Command objects can participate in dependency injection. This is useful if your command object has some custom validation logic which uses a Grails <a href="services.html">service</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">LoginCommand</span> <span class="directive">implements</span> grails.validation.Validateable {

    <span class="keyword">def</span> loginService

    <span class="predefined-type">String</span> username
    <span class="predefined-type">String</span> password

    <span class="directive">static</span> constraints = {
        username <span class="key">validator</span>: { val, obj -&gt;
            obj.loginService.canLogin(obj.username, obj.password)
        }
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example the command object interacts with the <code>loginService</code> bean which is injected by name from the Spring <code>ApplicationContext</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_binding_the_request_body_to_command_objects">Binding The Request Body To Command Objects</h4>
<div class="paragraph">
<p>When a request is made to a controller action which accepts a command object and the request contains a body, Grails will attempt to parse the body of the request based on the request content type and use the body to do data binding on the command object.  See the following example.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/bindingdemo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> bindingdemo

<span class="type">class</span> <span class="class">DemoController</span> {

    <span class="keyword">def</span> <span class="function">createWidget</span>(Widget w) {
        render <span class="string"><span class="delimiter">&quot;</span><span class="content">Name: </span><span class="inline"><span class="inline-delimiter">${</span>w?.name<span class="inline-delimiter">}</span></span><span class="content">, Size: </span><span class="inline"><span class="inline-delimiter">${</span>w?.size<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
    }
}

<span class="type">class</span> <span class="class">Widget</span> {
    <span class="predefined-type">String</span> name
    <span class="predefined-type">Integer</span> size
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ curl -H &quot;Content-Type: application/json&quot; -d '{&quot;name&quot;:&quot;Some Widget&quot;,&quot;42&quot;}'[size] localhost:8080/demo/createWidget
 Name: Some Widget, Size: 42

$ curl -H &quot;Content-Type: application/xml&quot; -d '&lt;widget&gt;&lt;name&gt;Some Other Widget&lt;/name&gt;&lt;size&gt;2112&lt;/size&gt;&lt;/widget&gt;' localhost:8080/bodybind/demo/createWidget
 Name: Some Other Widget, Size: 2112</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The request body will not be parsed under the following conditions:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The request method is GET</p>
</li>
<li>
<p>The request method is DELETE</p>
</li>
<li>
<p>The content length is 0</p>
</li>
</ul>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Note that the body of the request is being parsed to make that work.  Any attempt to read the body of the request after that will fail since the corresponding input stream will be empty.  The controller action can either use a command object or it can parse the body of the request on its own (either directly, or by referring to something like request.JSON), but cannot do both.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/bindingdemo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> bindingdemo

<span class="type">class</span> <span class="class">DemoController</span> {

    <span class="keyword">def</span> <span class="function">createWidget</span>(Widget w) {
        <span class="comment">// this will fail because it requires reading the body,</span>
        <span class="comment">// which has already been read.</span>
        <span class="keyword">def</span> json = request.JSON

        <span class="comment">// ...</span>

    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_working_with_lists_of_command_objects">Working with Lists of Command Objects</h4>
<div class="paragraph">
<p>A common use case for command objects is a Command Object that contains a collection of another:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">DemoController</span> {

    <span class="keyword">def</span> <span class="function">createAuthor</span>(AuthorCommand command) {
        <span class="comment">// ...</span>

    }

    <span class="type">class</span> <span class="class">AuthorCommand</span> {
        <span class="predefined-type">String</span> fullName
        <span class="predefined-type">List</span>&lt;BookCommand&gt; books
    }

    <span class="type">class</span> <span class="class">BookCommand</span> {
        <span class="predefined-type">String</span> title
        <span class="predefined-type">String</span> isbn
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>On this example, we want to create an Author with multiple Books.</p>
</div>
<div class="paragraph">
<p>In order to make this work from the UI layer, you can do the following in your GSP:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:form</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">submit-author-books</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">controller</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">demo</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">createAuthor</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
    <span class="tag">&lt;g:fieldValue</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">fullName</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
    <span class="tag">&lt;ul&gt;</span>
        <span class="tag">&lt;li&gt;</span>
            <span class="tag">&lt;g:fieldValue</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
            <span class="tag">&lt;g:fieldValue</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].isbn</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
        <span class="tag">&lt;/li&gt;</span>

        <span class="tag">&lt;li&gt;</span>
            <span class="tag">&lt;g:fieldValue</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[1].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
            <span class="tag">&lt;g:fieldValue</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[1].isbn</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
        <span class="tag">&lt;/li&gt;</span>
    <span class="tag">&lt;/ul&gt;</span>
<span class="tag">&lt;/g:form&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>There is also support for JSON, so you can submit the following with correct databinding</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="json">{
    <span class="key"><span class="delimiter">&quot;</span><span class="content">fullName</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Graeme Rocher</span><span class="delimiter">&quot;</span></span>,
    <span class="key"><span class="delimiter">&quot;</span><span class="content">books</span><span class="delimiter">&quot;</span></span>: [{
        <span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">The Definitive Guide to Grails</span><span class="delimiter">&quot;</span></span>,
        <span class="key"><span class="delimiter">&quot;</span><span class="content">isbn</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1111-343455-1111</span><span class="delimiter">&quot;</span></span>
    }, {
        <span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">The Definitive Guide to Grails 2</span><span class="delimiter">&quot;</span></span>,
        <span class="key"><span class="delimiter">&quot;</span><span class="content">isbn</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1111-343455-1112</span><span class="delimiter">&quot;</span></span>
    }],
}</code></pre>
</div>
</div>
</div>

<a name="7.1.11 Handling Duplicate Form Submissions"><!-- Legacy link --></a>
<h2 id="formtokens">8.1.11 Handling Duplicate Form Submissions</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/formtokens.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Grails has built-in support for handling duplicate form submissions using the "Synchronizer Token Pattern". To get started you define a token on the <a href="../ref/Tags/form.html">form</a> tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:form</span> <span class="attribute-name">useToken</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">true</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">...</span><span class="tag">&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Then in your controller code you can use the <a href="../ref/Controllers/withForm.html">withForm</a> method to handle valid and invalid requests:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">withForm {
   <span class="comment">// good request</span>
}.invalidToken {
   <span class="comment">// bad request</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you only provide the <a href="../ref/Controllers/withForm.html">withForm</a> method and not the chained <code>invalidToken</code> method then by default Grails will store the invalid token in a <code>flash.invalidToken</code> variable and redirect the request back to the original page. This can then be checked in the view:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:if</span> <span class="attribute-name">test</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${flash.invalidToken}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
  Don't click the button twice!
<span class="tag">&lt;/g:if&gt;</span></code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
The <a href="../ref/Controllers/withForm.html">withForm</a> tag makes use of the <a href="../ref/Controllers/session.html">session</a> and hence requires session affinity or clustered sessions if used in a cluster.
</td>
</tr>
</table>
</div>

<a name="7.1.12 Simple Type Converters"><!-- Legacy link --></a>
<h2 id="typeConverters">8.1.12 Simple Type Converters</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/typeConverters.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect2">
<h3 id="_type_conversion_methods">Type Conversion Methods</h3>
<div class="paragraph">
<p>If you prefer to avoid the overhead of <a href="theWebLayer.html#dataBinding">data binding</a> and simply want to convert incoming parameters (typically Strings) into another more appropriate type the <a href="../ref/Controllers/params.html">params</a> object has a number of convenience methods for each type:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> total = params.int(<span class="string"><span class="delimiter">'</span><span class="content">total</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above example uses the <code>int</code> method, and there are also methods for <code>boolean</code>, <code>long</code>, <code>char</code>, <code>short</code> and so on. Each of these methods is null-safe and safe from any parsing errors, so you don&#8217;t have to perform any additional checks on the parameters.</p>
</div>
<div class="paragraph">
<p>Each of the conversion methods allows a default value to be passed as an optional second argument.  The default value will be returned if a corresponding entry cannot be found in the map or if an error occurs during the conversion.  Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> total = params.int(<span class="string"><span class="delimiter">'</span><span class="content">total</span><span class="delimiter">'</span></span>, <span class="integer">42</span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>These same type conversion methods are also available on the <code>attrs</code> parameter of GSP tags.</p>
</div>
</div>
<div class="sect2">
<h3 id="_handling_multi_parameters">Handling Multi Parameters</h3>
<div class="paragraph">
<p>A common use case is dealing with multiple request parameters of the same name. For example you could get a query string such as <code>?name=Bob&amp;name=Judy</code>.</p>
</div>
<div class="paragraph">
<p>In this case dealing with one parameter and dealing with many has different semantics since Groovy&#8217;s iteration mechanics for <code>String</code> iterate over each character. To avoid this problem the <a href="../ref/Controllers/params.html">params</a> object provides a <code>list</code> method that always returns a list:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">for</span> (name <span class="keyword">in</span> params.list(<span class="string"><span class="delimiter">'</span><span class="content">name</span><span class="delimiter">'</span></span>)) {
    println name
}</code></pre>
</div>
</div>
</div>


<h2 id="controllerExceptionHandling">8.1.13 Declarative Controller Exception Handling</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Grails controllers support a simple mechanism for declarative exception handling.  If a controller declares a method that accepts a single argument and the argument type is <code>java.lang.Exception</code> or some subclass of <code>java.lang.Exception</code>, that method will be invoked any time an action in that controller throws an exception of that type.  See the following example.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/demo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> demo

<span class="type">class</span> <span class="class">DemoController</span> {

    <span class="keyword">def</span> <span class="function">someAction</span>() {
        <span class="comment">// do some work</span>
    }

    <span class="keyword">def</span> <span class="function">handleSQLException</span>(<span class="exception">SQLException</span> e) {
        render <span class="string"><span class="delimiter">'</span><span class="content">A SQLException Was Handled</span><span class="delimiter">'</span></span>
    }

    <span class="keyword">def</span> <span class="function">handleBatchUpdateException</span>(<span class="exception">BatchUpdateException</span> e) {
        redirect <span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">logging</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">batchProblem</span><span class="delimiter">'</span></span>
    }

    <span class="keyword">def</span> <span class="function">handleNumberFormatException</span>(<span class="exception">NumberFormatException</span> nfe) {
        [<span class="key">problemDescription</span>: <span class="string"><span class="delimiter">'</span><span class="content">A Number Was Invalid</span><span class="delimiter">'</span></span>]
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>That controller will behave as if it were written something like this&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/demo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> demo

<span class="type">class</span> <span class="class">DemoController</span> {

    <span class="keyword">def</span> <span class="function">someAction</span>() {
        <span class="keyword">try</span> {
            <span class="comment">// do some work</span>
        } <span class="keyword">catch</span> (<span class="exception">BatchUpdateException</span> e) {
            <span class="keyword">return</span> handleBatchUpdateException(e)
        } <span class="keyword">catch</span> (<span class="exception">SQLException</span> e) {
            <span class="keyword">return</span> handleSQLException(e)
        } <span class="keyword">catch</span> (<span class="exception">NumberFormatException</span> e) {
            <span class="keyword">return</span> handleNumberFormatException(e)
        }
    }

    <span class="keyword">def</span> <span class="function">handleSQLException</span>(<span class="exception">SQLException</span> e) {
        render <span class="string"><span class="delimiter">'</span><span class="content">A SQLException Was Handled</span><span class="delimiter">'</span></span>
    }

    <span class="keyword">def</span> <span class="function">handleBatchUpdateException</span>(<span class="exception">BatchUpdateException</span> e) {
        redirect <span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">logging</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">batchProblem</span><span class="delimiter">'</span></span>
    }

    <span class="keyword">def</span> <span class="function">handleNumberFormatException</span>(<span class="exception">NumberFormatException</span> nfe) {
        [<span class="key">problemDescription</span>: <span class="string"><span class="delimiter">'</span><span class="content">A Number Was Invalid</span><span class="delimiter">'</span></span>]
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The exception handler method names can be any valid method name.  The name is not what makes the method an exception handler, the <code>Exception</code> argument type is the important part.</p>
</div>
<div class="paragraph">
<p>The exception handler methods can do anything that a controller action can do including invoking <code>render</code>, <code>redirect</code>, returning a model, etc.</p>
</div>
<div class="paragraph">
<p>One way to share exception handler methods across multiple controllers is to use inheritance.  Exception handler methods are inherited into subclasses so an application could define the exception handlers in an abstract class that multiple controllers extend from.  Another way to share exception handler methods across multiple controllers is to use a trait, as shown below&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/com/demo/DatabaseExceptionHandler.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo

trait DatabaseExceptionHandler {
    <span class="keyword">def</span> <span class="function">handleSQLException</span>(<span class="exception">SQLException</span> e) {
        <span class="comment">// handle SQLException</span>
    }

    <span class="keyword">def</span> <span class="function">handleBatchUpdateException</span>(<span class="exception">BatchUpdateException</span> e) {
        <span class="comment">// handle BatchUpdateException</span>
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/com/demo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo

<span class="type">class</span> <span class="class">DemoController</span> <span class="directive">implements</span> DatabaseExceptionHandler {

    <span class="comment">// all of the exception handler methods defined</span>
    <span class="comment">// in DatabaseExceptionHandler will be added to</span>
    <span class="comment">// this class at compile time</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Exception handler methods must be present at compile time.  Specifically, exception handler methods which are runtime metaprogrammed onto a controller class are not supported.</p>
</div>

<a name="7.2 Groovy Server Pages"><!-- Legacy link --></a>
<h2 id="gsp">8.2 Groovy Server Pages</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Groovy Servers Pages (or GSP for short) is Grails' view technology. It is designed to be familiar for users of technologies such as ASP and JSP, but to be far more flexible and intuitive.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Although GSP can render any format, not just HTML, it is more designed around rendering markup. If you are looking for a way to simplify JSON responses take a look at <a href="webServices.html#jsonViews">JSON Views</a>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>GSPs live in the <code>grails-app/views</code> directory and are typically rendered automatically (by convention) or with the <a href="../ref/Controllers/render.html">render</a> method such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">render(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">index</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>A GSP is typically a mix of mark-up and GSP tags which aid in view rendering.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Although it is possible to have Groovy logic embedded in your GSP and doing this will be covered in this document, the practice is strongly discouraged. Mixing mark-up and code is a <strong>bad</strong> thing and most GSP pages contain no code and needn&#8217;t do so.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>A GSP typically has a "model" which is a set of variables that are used for view rendering. The model is passed to the GSP view from a controller. For example consider the following controller action:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>() {
    [<span class="key">book</span>: <span class="predefined-type">Book</span>.get(params.id)]
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This action will look up a <code>Book</code> instance and create a model that contains a key called <code>book</code>. This key can then be referenced within the GSP view using the name <code>book</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span>{book.title}</code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on <a href="security.html#xssPrevention">XSS prevention</a> for information on how to prevent XSS attacks.
</td>
</tr>
</table>
</div>

<a name="7.2.1 GSP Basics"><!-- Legacy link --></a>
<h2 id="GSPBasics">8.2.1 GSP Basics</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/GSPBasics.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>In the next view sections we&#8217;ll go through the basics of GSP and what is available to you. First off let&#8217;s cover some basic syntax that users of JSP and ASP should be familiar with.</p>
</div>
<div class="paragraph">
<p>GSP supports the usage of <code>&lt;% %&gt;</code> scriptlet blocks to embed Groovy code (again this is discouraged):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;html&gt;</span>
   <span class="tag">&lt;body&gt;</span>
     <span class="error">&lt;</span>% out <span class="error">&lt;</span><span class="error">&lt;</span> &quot;Hello GSP!&quot; %<span class="error">&gt;</span>
   <span class="tag">&lt;/body&gt;</span>
<span class="tag">&lt;/html&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also use the <code>&lt;%= %&gt;</code> syntax to output values:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;html&gt;</span>
   <span class="tag">&lt;body&gt;</span>
     <span class="error">&lt;</span>%=&quot;Hello GSP!&quot; %<span class="error">&gt;</span>
   <span class="tag">&lt;/body&gt;</span>
<span class="tag">&lt;/html&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>GSP also supports JSP-style server-side comments (which are not rendered in the HTML response) as the following example demonstrates:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;html&gt;</span>
   <span class="tag">&lt;body&gt;</span>
     <span class="error">&lt;</span>%-- This is my comment --%<span class="error">&gt;</span>
     <span class="error">&lt;</span>%=&quot;Hello GSP!&quot; %<span class="error">&gt;</span>
   <span class="tag">&lt;/body&gt;</span>
<span class="tag">&lt;/html&gt;</span></code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on <a href="security.html#xssPrevention">XSS prevention</a> for information on how to prevent XSS attacks.
</td>
</tr>
</table>
</div>

<a name="6.6.3 Variables and Scopes"><!-- Legacy link --></a>
<h2 id="variablesAndScopes">8.2.1.1 Variables and Scopes</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/GSPBasics/variablesAndScopes.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Within the <code>&lt;% %&gt;</code> brackets you can declare variables:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="error">&lt;</span>% now = new Date() %<span class="error">&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>and then access those variables later in the page:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="error">&lt;</span>%=now%<span class="error">&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Within the scope of a GSP there are a number of pre-defined variables, including:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>application</code> - The <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html">ServletContext</a> instance</p>
</li>
<li>
<p><code>applicationContext</code> The Spring <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html">ApplicationContext</a> instance</p>
</li>
<li>
<p><code>flash</code> - The <a href="../ref/Controllers/flash.html">flash</a> object</p>
</li>
<li>
<p><code>grailsApplication</code> - The <a href="http://docs.grails.org/3.2.11/api/grails/core/GrailsApplication.html">GrailsApplication</a> instance</p>
</li>
<li>
<p><code>out</code> - The response writer for writing to the output stream</p>
</li>
<li>
<p><code>params</code> - The <a href="../ref/Controllers/params.html">params</a> object for retrieving request parameters</p>
</li>
<li>
<p><code>request</code> - The <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html">HttpServletRequest</a> instance</p>
</li>
<li>
<p><code>response</code> - The <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletResponse.html">HttpServletResponse</a> instance</p>
</li>
<li>
<p><code>session</code> - <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSession.html">HttpSession</a> instance</p>
</li>
<li>
<p><code>webRequest</code> - The <a href="http://docs.grails.org/3.2.11/api/org/grails/web/servlet/mvc/GrailsWebRequest.html">GrailsWebRequest</a> instance</p>
</li>
</ul>
</div>

<a name="7.2.2.2 Logic and Iteration"><!-- Legacy link --></a>
<h2 id="logicAndIteration">8.2.1.2 Logic and Iteration</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/GSPBasics/logicAndIteration.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Using the <code>&lt;% %&gt;</code> syntax you can embed loops and so on using this syntax:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;html&gt;</span>
   <span class="tag">&lt;body&gt;</span>
      <span class="error">&lt;</span>% [1,2,3,4].each { num -<span class="error">&gt;</span> %<span class="error">&gt;</span>
         <span class="tag">&lt;p&gt;</span><span class="error">&lt;</span>%=&quot;Hello ${num}!&quot; %<span class="error">&gt;</span><span class="tag">&lt;/p&gt;</span>
      <span class="error">&lt;</span>%}%<span class="error">&gt;</span>
   <span class="tag">&lt;/body&gt;</span>
<span class="tag">&lt;/html&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>As well as logical branching:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;html&gt;</span>
   <span class="tag">&lt;body&gt;</span>
      <span class="error">&lt;</span>% if (params.hello == 'true')%<span class="error">&gt;</span>
      <span class="error">&lt;</span>%=&quot;Hello!&quot;%<span class="error">&gt;</span>
      <span class="error">&lt;</span>% else %<span class="error">&gt;</span>
      <span class="error">&lt;</span>%=&quot;Goodbye!&quot;%<span class="error">&gt;</span>
   <span class="tag">&lt;/body&gt;</span>
<span class="tag">&lt;/html&gt;</span></code></pre>
</div>
</div>

<a name="7.2.1.3 Page Directives"><!-- Legacy link --></a>
<h2 id="pageDirectives">8.2.1.3 Page Directives</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/GSPBasics/pageDirectives.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>GSP also supports a few JSP-style page directives.</p>
</div>
<div class="paragraph">
<p>The import directive lets you import classes into the page. However, it is rarely needed due to Groovy&#8217;s default imports and <a href="#tags">GSP Tags</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="error">&lt;</span>%@ page import=&quot;java.awt.*&quot; %<span class="error">&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>GSP also supports the contentType directive:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="error">&lt;</span>%@ page contentType=&quot;application/json&quot; %<span class="error">&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The contentType directive allows using GSP to render other formats.</p>
</div>

<a name="7.2.1.4 Expressions"><!-- Legacy link --></a>
<h2 id="expressions">8.2.1.4 Expressions</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/GSPBasics/expressions.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>In GSP the <code>&lt;%= %&gt;</code> syntax introduced earlier is rarely used due to the support for GSP expressions. A GSP expression is similar to a JSP EL expression or a Groovy GString and takes the form <code>${expr}</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;html&gt;</span>
  <span class="tag">&lt;body&gt;</span>
    Hello ${params.name}
  <span class="tag">&lt;/body&gt;</span>
<span class="tag">&lt;/html&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>However, unlike JSP EL you can have any Groovy expression within the <code>${..}</code> block.</p>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on <a href="security.html#xssPrevention">XSS prevention</a> for information on how to prevent XSS attacks.
</td>
</tr>
</table>
</div>

<a name="7.2.2 GSP Tags"><!-- Legacy link --></a>
<h2 id="tags">8.2.2 GSP Tags</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/tags.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Now that the less attractive JSP heritage has been set aside, the following sections cover GSP&#8217;s built-in tags, which are the preferred way to define GSP pages.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The section on <a href="#taglibs">Tag Libraries</a> covers how to add your own custom tag libraries.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>All built-in GSP tags start with the prefix <code>g:</code>. Unlike JSP, you don&#8217;t specify any tag library imports. If a tag starts with <code>g:</code> it is automatically assumed to be a GSP tag. An example GSP tag would look like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:example</span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>GSP tags can also have a body such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:example&gt;</span>
   Hello world
<span class="tag">&lt;/g:example&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Expressions can be passed into GSP tag attributes, if an expression is not used it will be assumed to be a String value:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:example</span> <span class="attribute-name">attr</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${new Date()}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
   Hello world
<span class="tag">&lt;/g:example&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Maps can also be passed into GSP tag attributes, which are often used for a named parameter style syntax:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:example</span> <span class="attribute-name">attr</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${new Date()}</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">attr2</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[one:1, two:2, three:3]</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
   Hello world
<span class="tag">&lt;/g:example&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that within the values of attributes you must use single quotes for Strings:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:example</span> <span class="attribute-name">attr</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${new Date()}</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">attr2</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[one:'one', two:'two']</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
   Hello world
<span class="tag">&lt;/g:example&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>With the basic syntax out the way, the next sections look at the tags that are built into Grails by default.</p>
</div>


<h2 id="tagVariablesAndScopes">8.2.2.1 Variables and Scopes</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/tags/tagVariablesAndScopes.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Variables can be defined within a GSP using the <a href="../ref/Tags/set.html">set</a> tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:set</span> <span class="attribute-name">var</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">now</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${new Date()}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Here we assign a variable called <code>now</code> to the result of a GSP expression (which simply constructs a new <code>java.util.Date</code> instance). You can also use the body of the <code>&lt;g:set&gt;</code> tag to define a variable:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:set</span> <span class="attribute-name">var</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">myHTML</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
   Some re-usable code on: ${new Date()}
<span class="tag">&lt;/g:set&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The assigned value can also be a bean from the applicationContext:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:set</span> <span class="attribute-name">var</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">bookService</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">bean</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">bookService</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Variables can also be placed in one of the following scopes:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>page</code> - Scoped to the current page (default)</p>
</li>
<li>
<p><code>request</code> - Scoped to the current request</p>
</li>
<li>
<p><code>flash</code> - Placed within <a href="../ref/Controllers/flash.html">flash</a> scope and hence available for the next request</p>
</li>
<li>
<p><code>session</code> - Scoped for the user session</p>
</li>
<li>
<p><code>application</code> - Application-wide scope.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>To specify the scope, use the <code>scope</code> attribute:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:set</span> <span class="attribute-name">var</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">now</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${new Date()}</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">scope</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">request</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>


<h2 id="tagLogicAndIteration">8.2.2.2 Logic and Iteration</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/tags/tagLogicAndIteration.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>GSP also supports logical and iterative tags out of the box. For logic there are <a href="../ref/Tags/if.html">if</a>, <a href="../ref/Tags/else.html">else</a> and <a href="../ref/Tags/elseif.html">elseif</a> tags for use with branching:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:if</span> <span class="attribute-name">test</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${session.role == 'admin'}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
   <span class="error">&lt;</span>%-- show administrative functions --%<span class="error">&gt;</span>
<span class="tag">&lt;/g:if&gt;</span>
<span class="tag">&lt;g:else&gt;</span>
   <span class="error">&lt;</span>%-- show basic functions --%<span class="error">&gt;</span>
<span class="tag">&lt;/g:else&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Use the <a href="../ref/Tags/each.html">each</a> and <a href="../ref/Tags/while.html">while</a> tags for iteration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:each</span> <span class="attribute-name">in</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${[1,2,3]}</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">var</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">num</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
   <span class="tag">&lt;p&gt;</span>Number ${num}<span class="tag">&lt;/p&gt;</span>
<span class="tag">&lt;/g:each&gt;</span>

<span class="tag">&lt;g:set</span> <span class="attribute-name">var</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">num</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${1}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;g:while</span> <span class="attribute-name">test</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${num &lt; 5 }</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
    <span class="tag">&lt;p&gt;</span>Number ${num++}<span class="tag">&lt;/p&gt;</span>
<span class="tag">&lt;/g:while&gt;</span></code></pre>
</div>
</div>

<a name="7.2.2.3 Search and Filtering"><!-- Legacy link --></a>
<h2 id="searchAndFiltering">8.2.2.3 Search and Filtering</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/tags/searchAndFiltering.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>If you have collections of objects you often need to sort and filter them. Use the <a href="../ref/Tags/findAll.html">findAll</a> and <a href="../ref/Tags/grep.html">grep</a> tags for these tasks:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml">Stephen King's Books:
<span class="tag">&lt;g:findAll</span> <span class="attribute-name">in</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${books}</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">expr</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">it.author == 'Stephen King'</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
     <span class="tag">&lt;p&gt;</span>Title: ${it.title}<span class="tag">&lt;/p&gt;</span>
<span class="tag">&lt;/g:findAll&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>expr</code> attribute contains a Groovy expression that can be used as a filter. The <a href="../ref/Tags/grep.html">grep</a> tag does a similar job, for example filtering by class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:grep</span> <span class="attribute-name">in</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${books}</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">filter</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">NonFictionBooks.class</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
     <span class="tag">&lt;p&gt;</span>Title: ${it.title}<span class="tag">&lt;/p&gt;</span>
<span class="tag">&lt;/g:grep&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Or using a regular expression:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:grep</span> <span class="attribute-name">in</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${books.title}</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">filter</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">~/.*?Groovy.*?/</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
     <span class="tag">&lt;p&gt;</span>Title: ${it}<span class="tag">&lt;/p&gt;</span>
<span class="tag">&lt;/g:grep&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The above example is also interesting due to its usage of GPath. GPath is an XPath-like language in Groovy. The <code>books</code> variable is a collection of <code>Book</code> instances. Since each <code>Book</code> has a <code>title</code>, you can obtain a list of Book titles using the expression <code>books.title</code>. Groovy will auto-magically iterate the collection, obtain each title, and return a new list!</p>
</div>

<a name="7.2.2.4 Links and Resources"><!-- Legacy link --></a>
<h2 id="linksAndResources">8.2.2.4 Links and Resources</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/tags/linksAndResources.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>GSP also features tags to help you manage linking to controllers and actions. The <a href="../ref/Tags/link.html">link</a> tag lets you specify controller and action name pairing and it will automatically work out the link based on the <a href="#urlmappings">URL Mappings</a>, even if you change them! For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:link</span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">id</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">1</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Book 1<span class="tag">&lt;/g:link&gt;</span>

<span class="tag">&lt;g:link</span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">id</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${currentBook.id}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>${currentBook.name}<span class="tag">&lt;/g:link&gt;</span>

<span class="tag">&lt;g:link</span> <span class="attribute-name">controller</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Book Home<span class="tag">&lt;/g:link&gt;</span>

<span class="tag">&lt;g:link</span> <span class="attribute-name">controller</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Book List<span class="tag">&lt;/g:link&gt;</span>

<span class="tag">&lt;g:link</span> <span class="attribute-name">url</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[action: 'list', controller: 'book']</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Book List<span class="tag">&lt;/g:link&gt;</span>

<span class="tag">&lt;g:link</span> <span class="attribute-name">params</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[sort: 'title', order: 'asc', author: currentBook.author]</span><span class="delimiter">&quot;</span></span>
        <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Book List<span class="tag">&lt;/g:link&gt;</span></code></pre>
</div>
</div>

<a name="7.2.2.5 Forms and Fields"><!-- Legacy link --></a>
<h2 id="formsAndFields">8.2.2.5 Forms and Fields</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/tags/formsAndFields.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_form_basics">Form Basics</h4>
<div class="paragraph">
<p>GSP supports many different tags for working with HTML forms and fields, the most basic of which is the <a href="../ref/Tags/form.html">form</a> tag. This is a controller/action aware version of the regular HTML form tag. The <code>url</code> attribute lets you specify which controller and action to map to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:form</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">myForm</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">url</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[controller:'book',action:'list']</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>...<span class="tag">&lt;/g:form&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case we create a form called <code>myForm</code> that submits to the <code>BookController&#8217;s `list</code> action. Beyond that all of the usual HTML attributes apply.</p>
</div>
</div>
<div class="sect3">
<h4 id="_form_fields">Form Fields</h4>
<div class="paragraph">
<p>In addition to easy construction of forms, GSP supports custom tags for dealing with different types of fields, including:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="../ref/Tags/textField.html">textField</a> - For input fields of type 'text'</p>
</li>
<li>
<p><a href="../ref/Tags/passwordField.html">passwordField</a> - For input fields of type 'password'</p>
</li>
<li>
<p><a href="../ref/Tags/checkBox.html">checkBox</a> - For input fields of type 'checkbox'</p>
</li>
<li>
<p><a href="../ref/Tags/radio.html">radio</a> - For input fields of type 'radio'</p>
</li>
<li>
<p><a href="../ref/Tags/hiddenField.html">hiddenField</a> - For input fields of type 'hidden'</p>
</li>
<li>
<p><a href="../ref/Tags/select.html">select</a> - For dealing with HTML select boxes</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Each of these allows GSP expressions for the value:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:textField</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">myField</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${myValue}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>GSP also contains extended helper versions of the above tags such as <a href="../ref/Tags/radioGroup.html">radioGroup</a> (for creating groups of <a href="../ref/Tags/radio.html">radio</a> tags), <a href="../ref/Tags/localeSelect.html">localeSelect</a>, <a href="../ref/Tags/currencySelect.html">currencySelect</a> and <a href="../ref/Tags/timeZoneSelect.html">timeZoneSelect</a> (for selecting locales, currencies and time zones respectively).</p>
</div>
</div>
<div class="sect3">
<h4 id="_multiple_submit_buttons">Multiple Submit Buttons</h4>
<div class="paragraph">
<p>The age old problem of dealing with multiple submit buttons is also handled elegantly with Grails using the <a href="../ref/Tags/actionSubmit.html">actionSubmit</a> tag. It is just like a regular submit, but lets you specify an alternative action to submit to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:actionSubmit</span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">Some update label</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">update</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
</div>

<a name="7.2.2.6 Tags as Method Calls"><!-- Legacy link --></a>
<h2 id="tagsAsMethodCalls">8.2.2.6 Tags as Method Calls</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/tags/tagsAsMethodCalls.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>One major difference between GSP tags and other tagging technologies is that GSP tags can be called as either regular tags or as method calls from <a href="#controllers">controllers</a>, <a href="#taglibs">tag libraries</a> or GSP views.</p>
</div>
<div class="sect3">
<h4 id="_tags_as_method_calls_from_gsps">Tags as method calls from GSPs</h4>
<div class="paragraph">
<p>Tags return their results as a String-like object (a <code>StreamCharBuffer</code> which has all of the same methods as String) instead of writing directly to the response when called as methods. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml">Static Resource: ${createLinkTo(dir: &quot;images&quot;, file: &quot;logo.jpg&quot;)}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is particularly useful for using a tag within an attribute:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;img</span> <span class="attribute-name">src</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${createLinkTo(dir: 'images', file: 'logo.jpg')}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>In view technologies that don&#8217;t support this feature you have to nest tags within tags, which becomes messy quickly and often has an adverse effect of WYSIWYG tools such as Dreamweaver that attempt to render the mark-up as it is not well-formed:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;img</span> <span class="attribute-name">src</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">&lt;g:createLinkTo dir=</span><span class="delimiter">&quot;</span></span><span class="attribute-name">images</span><span class="error">&quot;</span> <span class="attribute-name">file</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">logo.jpg</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>&quot; /<span class="error">&gt;</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_tags_as_method_calls_from_controllers_and_tag_libraries">Tags as method calls from Controllers and Tag Libraries</h4>
<div class="paragraph">
<p>You can also invoke tags from controllers and tag libraries. Tags within the default <code>g:</code> <a href="#namespaces">namespace</a> can be invoked without the prefix and a <code>StreamCharBuffer</code> result is returned:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> imageLocation = createLinkTo(<span class="key">dir</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">images</span><span class="delimiter">&quot;</span></span>, <span class="key">file</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">logo.jpg</span><span class="delimiter">&quot;</span></span>).toString()</code></pre>
</div>
</div>
<div class="paragraph">
<p>Prefix the namespace to avoid naming conflicts:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> imageLocation = g.createLinkTo(<span class="key">dir</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">images</span><span class="delimiter">&quot;</span></span>, <span class="key">file</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">logo.jpg</span><span class="delimiter">&quot;</span></span>).toString()</code></pre>
</div>
</div>
<div class="paragraph">
<p>For tags that use a <a href="#namespaces">custom namespace</a>, use that prefix for the method call. For example (from the <a href="http://grails.org/plugin/fckeditor">FCK Editor plugin</a>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> editor = fckeditor.editor(<span class="key">name</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">text</span><span class="delimiter">&quot;</span></span>, <span class="key">width</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">100%</span><span class="delimiter">&quot;</span></span>, <span class="key">height</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">400</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
</div>

<a name="7.2.3 Views and Templates"><!-- Legacy link --></a>
<h2 id="viewsAndTemplates">8.2.3 Views and Templates</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/viewsAndTemplates.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Grails also has the concept of templates. These are useful for partitioning your views into maintainable chunks, and combined with <a href="#layouts">Layouts</a> provide a highly re-usable mechanism for structured views.</p>
</div>
<div class="sect3">
<h4 id="_template_basics">Template Basics</h4>
<div class="paragraph">
<p>Grails uses the convention of placing an underscore before the name of a view to identify it as a template. For example, you might have a template that renders Books located at <code>grails-app/views/book/_bookTemplate.gsp</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;div</span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">id</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${book?.id}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
   <span class="tag">&lt;div&gt;</span>Title: ${book?.title}<span class="tag">&lt;/div&gt;</span>
   <span class="tag">&lt;div&gt;</span>Author: ${book?.author?.name}<span class="tag">&lt;/div&gt;</span>
<span class="tag">&lt;/div&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Use the <a href="../ref/Tags/render.html">render</a> tag to render this template from one of the views in <code>grails-app/views/book</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:render</span> <span class="attribute-name">template</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">bookTemplate</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">model</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[book: myBook]</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice how we pass into a model to use using the <code>model</code> attribute of the <code>render</code> tag. If you have multiple <code>Book</code> instances you can also render the template for each <code>Book</code> using the render tag with a <code>collection</code> attribute:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:render</span> <span class="attribute-name">template</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">bookTemplate</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">var</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">collection</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${bookList}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_shared_templates">Shared Templates</h4>
<div class="paragraph">
<p>In the previous example we had a template that was specific to the <code>BookController</code> and its views at <code>grails-app/views/book</code>. However, you may want to share templates across your application.</p>
</div>
<div class="paragraph">
<p>In this case you can place them in the root views directory at grails-app/views or any subdirectory below that location, and then with the template attribute use an absolute location starting with <code>/</code> instead of a relative location. For example if you had a template called <code>grails-app/views/shared/_mySharedTemplate.gsp</code>, you would reference it as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:render</span> <span class="attribute-name">template</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/shared/mySharedTemplate</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also use this technique to reference templates in any directory from any view or controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:render</span> <span class="attribute-name">template</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/book/bookTemplate</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">model</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[book: myBook]</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_the_template_namespace">The Template Namespace</h4>
<div class="paragraph">
<p>Since templates are used so frequently there is template namespace, called <code>tmpl</code>, available that makes using templates easier. Consider for example the following usage pattern:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:render</span> <span class="attribute-name">template</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">bookTemplate</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">model</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[book:myBook]</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>This can be expressed with the <code>tmpl</code> namespace as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;tmpl:bookTemplate</span> <span class="attribute-name">book</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${myBook}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_templates_in_controllers_and_tag_libraries">Templates in Controllers and Tag Libraries</h4>
<div class="paragraph">
<p>You can also render templates from controllers using the <a href="../ref/Controllers/render.html">render</a> controller method. This is useful for JavaScript heavy applications where you generate small HTML or data responses to partially update the current page instead of performing new request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">bookData</span>() {
    <span class="keyword">def</span> b = <span class="predefined-type">Book</span>.get(params.id)
    render(<span class="key">template</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">bookTemplate</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>:[<span class="key">book</span>:b])
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <a href="../ref/Controllers/render.html">render</a> controller method writes directly to the response, which is the most common behaviour. To instead obtain the result of template as a String you can use the <a href="../ref/Tags/render.html">render</a> tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">bookData</span>() {
    <span class="keyword">def</span> b = <span class="predefined-type">Book</span>.get(params.id)
    <span class="predefined-type">String</span> content = g.render(<span class="key">template</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">bookTemplate</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>:[<span class="key">book</span>:b])
    render content
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice the usage of the <code>g</code> namespace which tells Grails we want to use the <a href="#tagsAsMethodCalls">tag as method call</a> instead of the <a href="../ref/Controllers/render.html">render</a> method.</p>
</div>
</div>

<a name="7.2.4 Layouts with Sitemesh"><!-- Legacy link --></a>
<h2 id="layouts">8.2.4 Layouts with Sitemesh</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/layouts.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_creating_layouts">Creating Layouts</h4>
<div class="paragraph">
<p>Grails leverages <a href="http://sitemesh.org">Sitemesh</a>, a decorator engine, to support view layouts. Layouts are located in the <code>grails-app/views/layouts</code> directory. A typical layout can be seen below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;html&gt;</span>
    <span class="tag">&lt;head&gt;</span>
        <span class="tag">&lt;title&gt;</span><span class="tag">&lt;g:layoutTitle</span> <span class="attribute-name">default</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">An example decorator</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span><span class="tag">&lt;/title&gt;</span>
        <span class="tag">&lt;g:layoutHead</span> <span class="tag">/&gt;</span>
    <span class="tag">&lt;/head&gt;</span>
    <span class="tag">&lt;body</span> <span class="attribute-name">onload</span>=<span class="string"><span class="delimiter">&quot;</span><span class="predefined">$</span>{pageProperty(name:<span class="string"><span class="delimiter">'</span><span class="content">body.onload</span><span class="delimiter">'</span></span>)}<span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
        <span class="tag">&lt;div</span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">menu</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span><span class="comment">&lt;!--my common menu goes here--&gt;</span><span class="tag">&lt;/div&gt;</span>
        <span class="tag">&lt;div</span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">body</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
            <span class="tag">&lt;g:layoutBody</span> <span class="tag">/&gt;</span>
        <span class="tag">&lt;/div&gt;</span>
    <span class="tag">&lt;/body&gt;</span>
<span class="tag">&lt;/html&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The key elements are the <a href="../ref/Tags/layoutHead.html">layoutHead</a>, <a href="../ref/Tags/layoutTitle.html">layoutTitle</a> and <a href="../ref/Tags/layoutBody.html">layoutBody</a> tag invocations:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>layoutTitle</code> - outputs the target page&#8217;s title</p>
</li>
<li>
<p><code>layoutHead</code> - outputs the target page&#8217;s head tag contents</p>
</li>
<li>
<p><code>layoutBody</code> - outputs the target page&#8217;s body tag contents</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The previous example also demonstrates the <a href="../ref/Tags/pageProperty.html">pageProperty</a> tag which can be used to inspect and return aspects of the target page.</p>
</div>
</div>
<div class="sect3">
<h4 id="_triggering_layouts">Triggering Layouts</h4>
<div class="paragraph">
<p>There are a few ways to trigger a layout. The simplest is to add a meta tag to the view:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;html&gt;</span>
    <span class="tag">&lt;head&gt;</span>
        <span class="tag">&lt;title&gt;</span>An Example Page<span class="tag">&lt;/title&gt;</span>
        <span class="tag">&lt;meta</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">layout</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">content</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">main</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
    <span class="tag">&lt;/head&gt;</span>
    <span class="tag">&lt;body&gt;</span>This is my content!<span class="tag">&lt;/body&gt;</span>
<span class="tag">&lt;/html&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case a layout called <code>grails-app/views/layouts/main.gsp</code> will be used to layout the page. If we were to use the layout from the previous section the output would resemble this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;html&gt;</span>
    <span class="tag">&lt;head&gt;</span>
        <span class="tag">&lt;title&gt;</span>An Example Page<span class="tag">&lt;/title&gt;</span>
    <span class="tag">&lt;/head&gt;</span>
    <span class="tag">&lt;body</span> <span class="attribute-name">onload</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
        <span class="tag">&lt;div</span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">menu</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span><span class="comment">&lt;!--my common menu goes here--&gt;</span><span class="tag">&lt;/div&gt;</span>
        <span class="tag">&lt;div</span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">body</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
            This is my content!
        <span class="tag">&lt;/div&gt;</span>
    <span class="tag">&lt;/body&gt;</span>
<span class="tag">&lt;/html&gt;</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_specifying_a_layout_in_a_controller">Specifying A Layout In A Controller</h4>
<div class="paragraph">
<p>Another way to specify a layout is to specify the name of the layout by assigning a value to the "layout" property in a controller. For example, if you have a controller such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
    <span class="directive">static</span> layout = <span class="string"><span class="delimiter">'</span><span class="content">customer</span><span class="delimiter">'</span></span>

    <span class="keyword">def</span> <span class="function">list</span>() { ... }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can create a layout called <code>grails-app/views/layouts/customer.gsp</code> which will be applied to all views that the <code>BookController</code> delegates to.  The value of the "layout" property may contain a directory structure relative to the <code>grails-app/views/layouts/</code> directory.  For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
    <span class="directive">static</span> layout = <span class="string"><span class="delimiter">'</span><span class="content">custom/customer</span><span class="delimiter">'</span></span>

    <span class="keyword">def</span> <span class="function">list</span>() { ... }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Views rendered from that controller would be decorated with the <code>grails-app/views/layouts/custom/customer.gsp</code> template.</p>
</div>
</div>
<div class="sect3">
<h4 id="_layout_by_convention">Layout by Convention</h4>
<div class="paragraph">
<p>Another way to associate layouts is to use "layout by convention". For example, if you have this controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
    <span class="keyword">def</span> <span class="function">list</span>() { ... }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can create a layout called <code>grails-app/views/layouts/book.gsp</code>, which will be applied to all views that the <code>BookController</code> delegates to.</p>
</div>
<div class="paragraph">
<p>Alternatively, you can create a layout called <code>grails-app/views/layouts/book/list.gsp</code> which will only be applied to the <code>list</code> action within the <code>BookController</code>.</p>
</div>
<div class="paragraph">
<p>If you have both the above mentioned layouts in place the layout specific to the action will take precedence when the list action is executed.</p>
</div>
<div class="paragraph">
<p>If a layout may not be located using any of those conventions, the convention of last resort is to look for the application default layout which
is <code>grails-app/views/layouts/application.gsp</code>.  The name of the application default layout may be changed by defining a property
in <code>grails-app/conf/application.groovy</code> as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.sitemesh.default.layout = <span class="string"><span class="delimiter">'</span><span class="content">myLayoutName</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>With that property in place, the application default layout will be <code>grails-app/views/layouts/myLayoutName.gsp</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_inline_layouts">Inline Layouts</h4>
<div class="paragraph">
<p>Grails' also supports Sitemesh&#8217;s concept of inline layouts with the <a href="../ref/Tags/applyLayout.html">applyLayout</a> tag. This can be used to apply a layout to a template, URL or arbitrary section of content. This lets you even further modularize your view structure by "decorating" your template includes.</p>
</div>
<div class="paragraph">
<p>Some examples of usage can be seen below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:applyLayout</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">myLayout</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">template</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">bookTemplate</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">collection</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${books}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>

<span class="tag">&lt;g:applyLayout</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">myLayout</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">url</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">http://www.google.com</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>

<span class="tag">&lt;g:applyLayout</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">myLayout</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
The content to apply a layout to
<span class="tag">&lt;/g:applyLayout&gt;</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_server_side_includes">Server-Side Includes</h4>
<div class="paragraph">
<p>While the <a href="../ref/Tags/applyLayout.html">applyLayout</a> tag is useful for applying layouts to external content, if you simply want to include external content in the current page you use the <a href="../ref/Tags/include.html">include</a> tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:include</span> <span class="attribute-name">controller</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>You can even combine the <a href="../ref/Tags/include.html">include</a> tag and the <a href="../ref/Tags/applyLayout.html">applyLayout</a> tag for added flexibility:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:applyLayout</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">myLayout</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
   <span class="tag">&lt;g:include</span> <span class="attribute-name">controller</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;/g:applyLayout&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Finally, you can also call the <a href="../ref/Tags/include.html">include</a> tag from a controller or tag library as a method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> content = include(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>The resulting content will be provided via the return value of the <a href="../ref/Tags/include.html">include</a> tag.</p>
</div>
</div>

<a name="7.2.5 Static Resources"><!-- Legacy link --></a>
<h2 id="resources">8.2.5 Static Resources</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/resources.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Grails 3 integrates with the <a href="http://grails.org/plugins.html#plugin/asset-pipeline">Asset Pipeline plugin</a> to provide sophisticated static asset management. This plugin is installed by default in new Grails applications.</p>
</div>
<div class="paragraph">
<p>The basic way to include a link to a static asset in your application is to use the <a href="../ref/Tags/resource.html">resource</a> tag. This simple approach creates a URI pointing to the file.</p>
</div>
<div class="paragraph">
<p>However modern applications with dependencies on multiple JavaScript and CSS libraries and frameworks (as well as dependencies on multiple Grails plugins) require something more powerful.</p>
</div>
<div class="paragraph">
<p>The issues that the Asset-Pipeline plugin tackles are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Reduced Dependence - The plugin has compression, minification, and cache-digests built in.</p>
</li>
<li>
<p>Easy Debugging - Makes for easy debugging by keeping files separate in development mode.</p>
</li>
<li>
<p>Asset Bundling using require <a href="http://www.asset-pipeline.com/manual/#directives">directives</a>.</p>
</li>
<li>
<p>Web application performance tuning is difficult.</p>
</li>
<li>
<p>The need for a standard way to expose static assets in plugins and applications.</p>
</li>
<li>
<p>The need for extensible processing to make languages like LESS or Coffee first class citizens.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The asset-pipeline allows you to define your javascript or css requirements right at the top of the file and they get compiled on War creation.</p>
</div>
<div class="paragraph">
<p>Take a look at the <a href="http://www.asset-pipeline.com/manual">documentation</a> for the asset-pipeline to get started.</p>
</div>
<div class="paragraph">
<p>If you do not want to use the Asset-Pipeline plugin, you can serve the static assets from directories <code>src/main/resources/public</code> or <code>src/main/webapp</code>, but the latter one only gets included in WAR packaging but not in JAR packaging.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Static resources located in <code>src/main/resources/public</code> or <code>src/main/webapp</code> are resolved under the <code>/static/**</code> URI by default. You can change the URI pattern with the following configuration:
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yml"><span class="key">grails.resources.pattern</span>: <span class="string"><span class="content">/**</span></span></code></pre>
</div>
</div>

<a name="7.2.6 Sitemesh Content Blocks"><!-- Legacy link --></a>
<h2 id="sitemeshContentBlocks">8.2.6 Sitemesh Content Blocks</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/sitemeshContentBlocks.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Although it is useful to decorate an entire page sometimes you may find the need to decorate independent sections of your site. To do this you can use content blocks. To get started, partition the page to be decorated using the <code>&lt;content&gt;</code> tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;content</span> <span class="attribute-name">tag</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">navbar</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
... draw the navbar here...
<span class="tag">&lt;/content&gt;</span>

<span class="tag">&lt;content</span> <span class="attribute-name">tag</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">header</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
... draw the header here...
<span class="tag">&lt;/content&gt;</span>

<span class="tag">&lt;content</span> <span class="attribute-name">tag</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">footer</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
... draw the footer here...
<span class="tag">&lt;/content&gt;</span>

<span class="tag">&lt;content</span> <span class="attribute-name">tag</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">body</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
... draw the body here...
<span class="tag">&lt;/content&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Then within the layout you can reference these components and apply individual layouts to each:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;html&gt;</span>
    <span class="tag">&lt;body&gt;</span>
        <span class="tag">&lt;div</span> <span class="attribute-name">id</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">header</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
            <span class="tag">&lt;g:applyLayout</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">headerLayout</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
                <span class="tag">&lt;g:pageProperty</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">page.header</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
            <span class="tag">&lt;/g:applyLayout&gt;</span>
        <span class="tag">&lt;/div&gt;</span>
        <span class="tag">&lt;div</span> <span class="attribute-name">id</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">nav</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
            <span class="tag">&lt;g:applyLayout</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">navLayout</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
                <span class="tag">&lt;g:pageProperty</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">page.navbar</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
            <span class="tag">&lt;/g:applyLayout&gt;</span>
        <span class="tag">&lt;/div&gt;</span>
        <span class="tag">&lt;div</span> <span class="attribute-name">id</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">body</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
            <span class="tag">&lt;g:applyLayout</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">bodyLayout</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
                <span class="tag">&lt;g:pageProperty</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">page.body</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
            <span class="tag">&lt;/g:applyLayout&gt;</span>
        <span class="tag">&lt;/div&gt;</span>
        <span class="tag">&lt;div</span> <span class="attribute-name">id</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">footer</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
            <span class="tag">&lt;g:applyLayout</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">footerLayout</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
                <span class="tag">&lt;g:pageProperty</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">page.footer</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
            <span class="tag">&lt;/g:applyLayout&gt;</span>
        <span class="tag">&lt;/div&gt;</span>
    <span class="tag">&lt;/body&gt;</span>
<span class="tag">&lt;/html&gt;</span></code></pre>
</div>
</div>

<a name="7.2.7 Making Changes to a Deployed Application"><!-- Legacy link --></a>
<h2 id="makingChangesToADeployedApplication">8.2.7 Making Changes to a Deployed Application</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/makingChangesToADeployedApplication.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>One of the main issues with deploying a Grails application (or typically any servlet-based one) is that any change to the views requires that you redeploy your whole application. If all you want to do is fix a typo on a page, or change an image link, it can seem like a lot of unnecessary work. For such simple requirements, Grails does have a solution: the  <code>grails.gsp.view.dir</code>  configuration setting.</p>
</div>
<div class="paragraph">
<p>How does this work? The first step is to decide where the GSP files should go. Let&#8217;s say we want to keep them unpacked in a  <code>/var/www/grails/my-app</code>  directory. We add these two lines to  <code>grails-app/conf/application.groovy</code> :</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.gsp.enable.reload = <span class="predefined-constant">true</span>
grails.gsp.view.dir = <span class="string"><span class="delimiter">&quot;</span><span class="content">/var/www/grails/my-app/</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The first line tells Grails that modified GSP files should be reloaded at runtime. If you don&#8217;t have this setting, you can make as many changes as you like but they won&#8217;t be reflected in the running application until you restart. The second line tells Grails where to load the views and layouts from.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The trailing slash on the  <code>grails.gsp.view.dir</code>  value is important! Without it, Grails will look for views in the parent directory.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Setting "grails.gsp.view.dir" is optional. If it&#8217;s not specified, you can update files directly to the application server&#8217;s deployed war directory. Depending on the application server, these files might get overwritten when the server is restarted. Most application servers support "exploded war deployment" which is recommended in this case.</p>
</div>
<div class="paragraph">
<p>With those settings in place, all you need to do is copy the views from your web application to the external directory. On a Unix-like system, this would look something like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">mkdir -p /var/www/grails/my-app/grails-app/views
cp -R grails-app/views<span class="comment">/* /var/www/grails/my-app/grails-app/views</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The key point here is that you must retain the view directory structure, including the  <code>grails-app/views</code>  bit. So you end up with the path  <code>/var/www/grails/my-app/grails-app/views/&#8230;&#8203;</code> .</p>
</div>
<div class="paragraph">
<p>One thing to bear in mind with this technique is that every time you modify a GSP, it uses up permgen space. So at some point you will eventually hit "out of permgen space" errors unless you restart the server. So this technique is not recommended for frequent or large changes to the views.</p>
</div>
<div class="paragraph">
<p>There are also some System properties to control GSP reloading:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"><strong>Name</strong></th>
<th class="tableblock halign-left valign-top"><strong>Description</strong></th>
<th class="tableblock halign-left valign-top"><strong>Default</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">grails.gsp.enable.reload</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">alternative system property for enabling the GSP reload mode without changing <code>application.groovy</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">grails.gsp.reload.interval</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">interval between checking the lastmodified time of the gsp source file</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">unit is milliseconds</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">5000</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">grails.gsp.reload.granularity</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">the number of milliseconds leeway to give before deciding a file is out of date. this is needed because different roundings usually cause a 1000ms difference in lastmodified times</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">1000</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>GSP reloading is supported for precompiled GSPs since Grails 1.3.5 .</p>
</div>

<a name="7.2.8 GSP Debugging"><!-- Legacy link --></a>
<h2 id="GSPDebugging">8.2.8 GSP Debugging</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/gsp/GSPDebugging.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_viewing_the_generated_source_code">Viewing the generated source code</h4>
<div class="ulist">
<ul>
<li>
<p>Adding "?showSource=true" or "&amp;showSource=true" to the url shows the generated Groovy source code for the view instead of rendering it. It won&#8217;t show the source code of included templates. This only works in development mode</p>
</li>
<li>
<p>The saving of all generated source code can be activated by setting the property "grails.views.gsp.keepgenerateddir" (in <code>application.groovy</code>) . It must point to a directory that exists and is writable.</p>
</li>
<li>
<p>During "grails war" gsp pre-compilation, the generated source code is stored in grails.project.work.dir/gspcompile (usually in ~/.grails/(grails_version)/projects/(project name)/gspcompile).</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_debugging_gsp_code_with_a_debugger">Debugging GSP code with a debugger</h4>
<div class="ulist">
<ul>
<li>
<p>See <a href="http://contraptionsforprogramming.blogspot.com/2010/08/debuggable-gsps-in-springsource-tool.html">Debugging GSP in STS</a></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_viewing_information_about_templates_used_to_render_a_single_url">Viewing information about templates used to render a single url</h4>
<div class="paragraph">
<p>GSP templates are reused in large web applications by using the <code>g:render</code> taglib. Several small templates can be used to render a single page.
It might be hard to find out what GSP template actually renders the html seen in the result.
The debug templates -feature adds html comments to the output. The comments contain debug information about gsp templates used to render the page.</p>
</div>
<div class="paragraph">
<p>Usage is simple: append "?debugTemplates" or "&amp;debugTemplates" to the url and view the source of the result in your browser.
"debugTemplates" is restricted to development mode. It won&#8217;t work in production.</p>
</div>
<div class="paragraph">
<p>Here is an example of comments added by debugTemplates :</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;!-- GSP <span class="error">#</span><span class="integer">2</span> START <span class="key">template</span>: <span class="regexp"><span class="delimiter">/</span><span class="content">home</span><span class="delimiter">/</span></span>...<span class="regexp"><span class="delimiter">/</span><span class="content">views</span><span class="delimiter">/</span></span>_carousel.gsp
     <span class="key">precompiled</span>: <span class="predefined-constant">false</span> <span class="key">lastmodified</span>: ... --&gt;
.
.
.
&lt;!-- GSP <span class="error">#</span><span class="integer">2</span> END <span class="key">template</span>: <span class="regexp"><span class="delimiter">/</span><span class="content">home</span><span class="delimiter">/</span></span>...<span class="regexp"><span class="delimiter">/</span><span class="content">views</span><span class="delimiter">/</span></span>_carousel.gsp
     rendering <span class="key">time</span>: <span class="integer">115</span> ms --&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Each comment block has a unique id so that you can find the start &amp; end of each template call.</p>
</div>
</div>

<a name="7.3 Tag Libraries"><!-- Legacy link --></a>
<h2 id="taglibs">8.3 Tag Libraries</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/taglibs.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Like <a href="http://www.oracle.com/technetwork/java/javaee/jsp/index.html">Java Server Pages</a> (JSP), GSP supports the concept of custom tag libraries. Unlike JSP, Grails' tag library mechanism is simple, elegant and completely reloadable at runtime.</p>
</div>
<div class="paragraph">
<p>Quite simply, to create a tag library create a Groovy class that ends with the convention <code>TagLib</code> and place it within the <code>grails-app/taglib</code> directory:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleTagLib</span> {

}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now to create a tag create a Closure property that takes two arguments: the tag attributes and the body content:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleTagLib</span> {
    <span class="keyword">def</span> simple = { attrs, body -&gt;

    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>attrs</code> argument is a Map of the attributes of the tag, whilst the <code>body</code> argument is a Closure that returns the body content when invoked:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleTagLib</span> {
    <span class="keyword">def</span> emoticon = { attrs, body -&gt;
       out &lt;&lt; body() &lt;&lt; (attrs.happy == <span class="string"><span class="delimiter">'</span><span class="content">true</span><span class="delimiter">'</span></span> ? <span class="string"><span class="delimiter">&quot;</span><span class="content"> :-)</span><span class="delimiter">&quot;</span></span> : <span class="string"><span class="delimiter">&quot;</span><span class="content"> :-(</span><span class="delimiter">&quot;</span></span>)
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>As demonstrated above there is an implicit <code>out</code> variable that refers to the output <code>Writer</code> which you can use to append content to the response. Then you can reference the tag inside your GSP; no imports are necessary:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:emoticon</span> <span class="attribute-name">happy</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">true</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Hi John<span class="tag">&lt;/g:emoticon&gt;</span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
To help IDEs autocomplete tag attributes, you should add Javadoc comments to your tag closures with <code>@attr</code> descriptions. Since taglibs use Groovy code it can be difficult to reliably detect all usable attributes.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleTagLib</span> {

    <span class="comment">/**
     * Renders the body with an emoticon.
     *
     * @attr happy whether to show a happy emoticon ('true') or
     * a sad emoticon ('false')
     */</span>
    <span class="keyword">def</span> emoticon = { attrs, body -&gt;
       out &lt;&lt; body() &lt;&lt; (attrs.happy == <span class="string"><span class="delimiter">'</span><span class="content">true</span><span class="delimiter">'</span></span> ? <span class="string"><span class="delimiter">&quot;</span><span class="content"> :-)</span><span class="delimiter">&quot;</span></span> : <span class="string"><span class="delimiter">&quot;</span><span class="content"> :-(</span><span class="delimiter">&quot;</span></span>)
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>and any mandatory attributes should include the REQUIRED keyword, e.g.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleTagLib</span> {

    <span class="comment">/**
     * Creates a new password field.
     *
     * @attr name REQUIRED the field name
     * @attr value the field value
     */</span>
    <span class="keyword">def</span> passwordField = { attrs -&gt;
        attrs.type = <span class="string"><span class="delimiter">&quot;</span><span class="content">password</span><span class="delimiter">&quot;</span></span>
        attrs.tagName = <span class="string"><span class="delimiter">&quot;</span><span class="content">passwordField</span><span class="delimiter">&quot;</span></span>
        fieldImpl(out, attrs)
    }
}</code></pre>
</div>
</div>


<h2 id="taglibVariablesAndScopes">8.3.1 Variables and Scopes</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/taglibs/taglibVariablesAndScopes.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Within the scope of a tag library there are a number of pre-defined variables including:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>actionName</code> - The currently executing action name</p>
</li>
<li>
<p><code>controllerName</code> - The currently executing controller name</p>
</li>
<li>
<p><code>flash</code> - The <a href="../ref/Controllers/flash.html">flash</a> object</p>
</li>
<li>
<p><code>grailsApplication</code> - The <a href="http://docs.grails.org/3.2.11/api/grails/core/GrailsApplication.html">GrailsApplication</a> instance</p>
</li>
<li>
<p><code>out</code> - The response writer for writing to the output stream</p>
</li>
<li>
<p><code>pageScope</code> - A reference to the <a href="../ref/Tag%20Libraries/pageScope.html">pageScope</a> object used for GSP rendering (i.e. the binding)</p>
</li>
<li>
<p><code>params</code> - The <a href="../ref/Controllers/params.html">params</a> object for retrieving request parameters</p>
</li>
<li>
<p><code>pluginContextPath</code> - The context path to the plugin that contains the tag library</p>
</li>
<li>
<p><code>request</code> - The <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html">HttpServletRequest</a> instance</p>
</li>
<li>
<p><code>response</code> - The <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletResponse.html">HttpServletResponse</a> instance</p>
</li>
<li>
<p><code>servletContext</code> - The <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html">ServletContext</a> instance</p>
</li>
<li>
<p><code>session</code> - The <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSession.html">HttpSession</a> instance</p>
</li>
</ul>
</div>

<a name="7.3.2 Simple Tags"><!-- Legacy link --></a>
<h2 id="simpleTags">8.3.2 Simple Tags</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/taglibs/simpleTags.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>As demonstrated in the previous example it is easy to write simple tags that have no body and just output content. Another example is a <code>dateFormat</code> style tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> dateFormat = { attrs, body -&gt;
    out &lt;&lt; <span class="keyword">new</span> java.text.SimpleDateFormat(attrs.format).format(attrs.date)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above uses Java&#8217;s <code>SimpleDateFormat</code> class to format a date and then write it to the response. The tag can then be used within a GSP as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:dateFormat</span> <span class="attribute-name">format</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">dd-MM-yyyy</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">date</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${new Date()}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>With simple tags sometimes you need to write HTML mark-up to the response. One approach would be to embed the content directly:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> formatBook = { attrs, body -&gt;
    out &lt;&lt; <span class="string"><span class="delimiter">&quot;</span><span class="content">&lt;div id=</span><span class="char">\&quot;</span><span class="inline"><span class="inline-delimiter">${</span>attrs.book.id<span class="inline-delimiter">}</span></span><span class="char">\&quot;</span><span class="content">&gt;</span><span class="delimiter">&quot;</span></span>
    out &lt;&lt; <span class="string"><span class="delimiter">&quot;</span><span class="content">Title : </span><span class="inline"><span class="inline-delimiter">${</span>attrs.book.title<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
    out &lt;&lt; <span class="string"><span class="delimiter">&quot;</span><span class="content">&lt;/div&gt;</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Although this approach may be tempting it is not very clean. A better approach would be to reuse the <a href="../ref/Tags/render.html">render</a> tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> formatBook = { attrs, body -&gt;
    out &lt;&lt; render(<span class="key">template</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">bookTemplate</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: [<span class="key">book</span>: attrs.book])
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>And then have a separate GSP template that does the actual rendering.</p>
</div>

<a name="7.3.3 Logical Tags"><!-- Legacy link --></a>
<h2 id="logicalTags">8.3.3 Logical Tags</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/taglibs/logicalTags.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>You can also create logical tags where the body of the tag is only output once a set of conditions have been met. An example of this may be a set of security tags:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> isAdmin = { attrs, body -&gt;
    <span class="keyword">def</span> user = attrs.user
    <span class="keyword">if</span> (user &amp;&amp; checkUserPrivs(user)) {
        out &lt;&lt; body()
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The tag above checks if the user is an administrator and only outputs the body content if he/she has the correct set of access privileges:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:isAdmin</span> <span class="attribute-name">user</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${myUser}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
    // some restricted content
<span class="tag">&lt;/g:isAdmin&gt;</span></code></pre>
</div>
</div>

<a name="7.3.4 Iterative Tags"><!-- Legacy link --></a>
<h2 id="iterativeTags">8.3.4 Iterative Tags</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/taglibs/iterativeTags.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Iterative tags are easy too, since you can invoke the body multiple times:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> repeat = { attrs, body -&gt;
    attrs.times?.toInteger()?.times { num -&gt;
        out &lt;&lt; body(num)
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example we check for a <code>times</code> attribute and if it exists convert it to a number, then use Groovy&#8217;s <code>times</code> method to iterate the specified number of times:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:repeat</span> <span class="attribute-name">times</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">3</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;p&gt;</span>Repeat this 3 times! Current repeat = ${it}<span class="tag">&lt;/p&gt;</span>
<span class="tag">&lt;/g:repeat&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice how in this example we use the implicit <code>it</code> variable to refer to the current number. This works because when we invoked the body we passed in the current value inside the iteration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">out &lt;&lt; body(num)</code></pre>
</div>
</div>
<div class="paragraph">
<p>That value is then passed as the default variable <code>it</code> to the tag. However, if you have nested tags this can lead to conflicts, so you should instead name the variables that the body uses:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> repeat = { attrs, body -&gt;
    <span class="keyword">def</span> var = attrs.var ?: <span class="string"><span class="delimiter">&quot;</span><span class="content">num</span><span class="delimiter">&quot;</span></span>
    attrs.times?.toInteger()?.times { num -&gt;
        out &lt;&lt; body((var):num)
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here we check if there is a <code>var</code> attribute and if there is use that as the name to pass into the body invocation on this line:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">out &lt;&lt; body((var):num)</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Take notice to the usage of the parenthesis around the variable name. If you omit these Groovy assumes you are using a String key and not referring to the variable itself.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Now we can change the usage of the tag as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:repeat</span> <span class="attribute-name">times</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">3</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">var</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">j</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;p&gt;</span>Repeat this 3 times! Current repeat = ${j}<span class="tag">&lt;/p&gt;</span>
<span class="tag">&lt;/g:repeat&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice how we use the <code>var</code> attribute to define the name of the variable <code>j</code> and then we are able to reference that variable within the body of the tag.</p>
</div>

<a name="7.3.5 Tag Namespaces"><!-- Legacy link --></a>
<h2 id="namespaces">8.3.5 Tag Namespaces</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/taglibs/namespaces.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>By default, tags are added to the default Grails namespace and are used with the <code>g:</code> prefix in GSP pages. However, you can specify a different namespace by adding a static property to your <code>TagLib</code> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimpleTagLib</span> {
    <span class="directive">static</span> namespace = <span class="string"><span class="delimiter">&quot;</span><span class="content">my</span><span class="delimiter">&quot;</span></span>

    <span class="keyword">def</span> example = { attrs -&gt;
        ...
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here we have specified a <code>namespace</code> of <code>my</code> and hence the tags in this tag lib must then be referenced from GSP pages like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;my:example</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">...</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>where the prefix is the same as the value of the static <code>namespace</code> property. Namespaces are particularly useful for plugins.</p>
</div>
<div class="paragraph">
<p>Tags within namespaces can be invoked as methods using the namespace as a prefix to the method call:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">out &lt;&lt; my.example(<span class="key">name</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">foo</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>This works from GSP, controllers or tag libraries</p>
</div>

<a name="7.3.6 Using JSP Tag Libraries"><!-- Legacy link --></a>
<h2 id="usingJSPTagLibraries">8.3.6 Using JSP Tag Libraries</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/taglibs/usingJSPTagLibraries.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>In addition to the simplified tag library mechanism provided by GSP, you can also use JSP tags from GSP. To do so simply declare the JSP to use with the <code>taglib</code> directive:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="error">&lt;</span>%@ taglib prefix=&quot;fmt&quot; uri=&quot;http://java.sun.com/jsp/jstl/fmt&quot; %<span class="error">&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Besides this you have to configure Grails to scan for the JSP tld files.
This is configured with the <code>grails.gsp.tldScanPattern</code> setting. It accepts a comma separated String value. Spring&#8217;s PathMatchingResourcePatternResolver is used to resolve the patterns.</p>
</div>
<div class="paragraph">
<p>For example you could scan for all available tld files by adding this to <code>application.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.gsp.tldScanPattern=<span class="string"><span class="delimiter">'</span><span class="content">classpath*:/META-INF/*.tld,/WEB-INF/tld/*.tld</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>JSTL standard library is no more added as a dependency by default. In case you are using JSTL, you should also add these dependencies to <code>build.gradle</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">runtime <span class="string"><span class="delimiter">'</span><span class="content">javax.servlet:jstl:1.1.2</span><span class="delimiter">'</span></span>
        runtime <span class="string"><span class="delimiter">'</span><span class="content">taglibs:standard:1.1.2</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Then you can use JSP tags like any other tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;fmt:formatNumber</span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${10}</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">pattern</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">.00</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>With the added bonus that you can invoke JSP tags like methods:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span>{fmt.formatNumber(<span class="key">value</span>:<span class="integer">10</span>, <span class="key">pattern</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">.00</span><span class="delimiter">&quot;</span></span>)}</code></pre>
</div>
</div>

<a name="7.3.7 Tag return value"><!-- Legacy link --></a>
<h2 id="tagReturnValue">8.3.7 Tag return value</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/taglibs/tagReturnValue.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>A taglib can be used in a GSP as an ordinary tag or it might be used as a function in other taglibs or GSP expressions.</p>
</div>
<div class="paragraph">
<p>Internally Grails intercepts calls to taglib closures.
The "out" that is available in a taglib is mapped to a <code>java.io.Writer</code> implementation that writes to a buffer
that "captures" the output of the taglib call. This buffer is the return value of a tag library call when it&#8217;s
used as a function.</p>
</div>
<div class="paragraph">
<p>If the tag is listed in the library&#8217;s static <code>returnObjectForTags</code> array, then its return value will written to
the output when it&#8217;s used as a normal tag. The return value of the tag lib closure will be returned as-is
if it&#8217;s used as a function in GSP expressions or other taglibs.</p>
</div>
<div class="paragraph">
<p>If the tag is not included in the returnObjectForTags array, then its return value will be discarded.
Using "out" to write output in returnObjectForTags is not supported.</p>
</div>
<div class="paragraph">
<p>Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ObjectReturningTagLib</span> {
    <span class="directive">static</span> namespace = <span class="string"><span class="delimiter">&quot;</span><span class="content">cms</span><span class="delimiter">&quot;</span></span>
    <span class="directive">static</span> returnObjectForTags = [<span class="string"><span class="delimiter">'</span><span class="content">content</span><span class="delimiter">'</span></span>]

    <span class="keyword">def</span> content = { attrs, body -&gt;
        CmsContent.findByCode(attrs.code)?.content
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Given this example cms.content(code:'something') call in another taglib or GSP expression would return the value "CmsContent.content" directly to the caller without
wrapping the return value in a buffer. It might be worth doing so also because of performance optimization reasons. There is no need to wrap the
tag return value in an output buffer in such cases.</p>
</div>

<a name="7.4 URL Mappings"><!-- Legacy link --></a>
<h2 id="urlmappings">8.4 URL Mappings</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Throughout the documentation so far the convention used for URLs has been the default of <code>/controller/action/id</code>. However, this convention is not hard wired into Grails and is in fact controlled by a URL Mappings class located at <code>grails-app/controllers/mypackage/UrlMappings.groovy</code>.</p>
</div>
<div class="paragraph">
<p>The <code>UrlMappings</code> class contains a single property called <code>mappings</code> that has been assigned a block of code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> mypackage

<span class="type">class</span> <span class="class">UrlMappings</span> {
    <span class="directive">static</span> mappings = {
    }
}</code></pre>
</div>
</div>

<a name="7.4.1 Mapping to Controllers and Actions"><!-- Legacy link --></a>
<h2 id="mappingToControllersAndActions">8.4.1 Mapping to Controllers and Actions</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/mappingToControllersAndActions.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>To create a simple mapping simply use a relative URL as the method name and specify named parameters for the controller and action to map to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/product</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case we&#8217;ve mapped the URL <code>/product</code> to the <code>list</code> action of the <code>ProductController</code>. Omit the action definition to map to the default action of the controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/product</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>An alternative syntax is to assign the controller and action to use within a block passed to the method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/product</span><span class="delimiter">&quot;</span></span> {
    controller = <span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>
    action = <span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Which syntax you use is largely dependent on personal preference.</p>
</div>
<div class="paragraph">
<p>If you have mappings that all fall under a particular path you can group mappings with the <code>group</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">group <span class="string"><span class="delimiter">&quot;</span><span class="content">/product</span><span class="delimiter">&quot;</span></span>, {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/apple</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>, <span class="key">id</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">apple</span><span class="delimiter">&quot;</span></span>)
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/htc</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>, <span class="key">id</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">htc</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also create nested <code>group</code> url mappings:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">group <span class="string"><span class="delimiter">&quot;</span><span class="content">/store</span><span class="delimiter">&quot;</span></span>, {
    group <span class="string"><span class="delimiter">&quot;</span><span class="content">/product</span><span class="delimiter">&quot;</span></span>, {
        <span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>)
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To rewrite one URI onto another explicit URI (rather than a controller/action pair) do something like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/hello</span><span class="delimiter">&quot;</span></span>(<span class="key">uri</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/hello.dispatch</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Rewriting specific URIs is often useful when integrating with other frameworks.</p>
</div>

<a name="7.4.3 Mapping to REST resources"><!-- Legacy link --></a>
<h2 id="restfulMappings">8.4.2 Mapping to REST resources</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/restfulMappings.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Since Grails 2.3, it possible to create RESTful URL mappings that map onto controllers by convention. The syntax to do so is as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>You define a base URI and the name of the controller to map to using the <code>resources</code> parameter. The above mapping will result in the following URLs:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URI</th>
<th class="tableblock halign-left valign-top">Grails Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">index</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/create</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">create</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">save</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">show</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}/edit</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">edit</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">PUT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">update</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DELETE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">delete</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>If you are not sure which mapping will be generated for your case just run the command <code>url-mappings-report</code> in your grails console. It will give you a really neat report for all the url mappings.</p>
</div>
<div class="paragraph">
<p>If you wish to include or exclude any of the generated URL mappings you can do so with the <code>includes</code> or <code>excludes</code> parameter, which accepts the name of the Grails action to include or exclude:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>, <span class="key">excludes</span>:[<span class="string"><span class="delimiter">'</span><span class="content">delete</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">update</span><span class="delimiter">'</span></span>])

or

<span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>, <span class="key">includes</span>:[<span class="string"><span class="delimiter">'</span><span class="content">index</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">show</span><span class="delimiter">'</span></span>])</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_explicit_rest_mappings">Explicit REST Mappings</h4>
<div class="paragraph">
<p>As of Grails 3.1, if you prefer not to rely on a <code>resources</code> mapping to define your mappings then you can prefix any URL mapping with the HTTP method name (in lower case) to indicate the HTTP method it applies to. The following URL mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Is equivalent to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">get <span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">index</span><span class="delimiter">&quot;</span></span>)
get <span class="string"><span class="delimiter">&quot;</span><span class="content">/books/create</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">create</span><span class="delimiter">&quot;</span></span>)
post <span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">save</span><span class="delimiter">&quot;</span></span>)
get <span class="string"><span class="delimiter">&quot;</span><span class="content">/books/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>)
get <span class="string"><span class="delimiter">&quot;</span><span class="content">/books/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">/edit</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">edit</span><span class="delimiter">&quot;</span></span>)
put <span class="string"><span class="delimiter">&quot;</span><span class="content">/books/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">update</span><span class="delimiter">&quot;</span></span>)
delete <span class="string"><span class="delimiter">&quot;</span><span class="content">/books/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">delete</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice how the HTTP method name is prefixed prior to each URL mapping definition.</p>
</div>
</div>
<div class="sect3">
<h4 id="_single_resources">Single resources</h4>
<div class="paragraph">
<p>A single resource is a resource for which there is only one (possibly per user) in the system. You can create a single resource using the <code>resource</code> parameter (as opposed to <code>resources</code>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/book</span><span class="delimiter">&quot;</span></span>(<span class="key">resource</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>This results in the following URL mappings:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URI</th>
<th class="tableblock halign-left valign-top">Grails Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book/create</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">create</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">save</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">show</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book/edit</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">edit</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">PUT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">update</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DELETE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">delete</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>The main difference is that the id is not included in the URL mapping.</p>
</div>
</div>
<div class="sect3">
<h4 id="_nested_resources">Nested Resources</h4>
<div class="paragraph">
<p>You can nest resource mappings to generate child resources. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>) {
  <span class="string"><span class="delimiter">&quot;</span><span class="content">/authors</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">author</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above will result in the following URL mappings:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URL</th>
<th class="tableblock halign-left valign-top">Grails Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">index</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors/create</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">create</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">save</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">show</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors/edit/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">edit</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">PUT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">update</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DELETE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">delete</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>You can also nest regular URL mappings within a resource mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>) {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/publisher</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">publisher</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will result in the following URL being available:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URL</th>
<th class="tableblock halign-left valign-top">Grails Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/publisher</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">index</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>To map a URI directly below a resource then use a collection block:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>) {
    collection {
        <span class="string"><span class="delimiter">&quot;</span><span class="content">/publisher</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">publisher</span><span class="delimiter">&quot;</span></span>)
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will result in the following URL being available (without the ID):</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URL</th>
<th class="tableblock halign-left valign-top">Grails Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/publisher</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">index</p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect3">
<h4 id="_linking_to_restful_mappings">Linking to RESTful Mappings</h4>
<div class="paragraph">
<p>You can link to any URL mapping created with the <code>g:link</code> tag provided by Grails simply by referencing the controller and action to link to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;<span class="key">g</span>:link controller=<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span> action=<span class="string"><span class="delimiter">&quot;</span><span class="content">index</span><span class="delimiter">&quot;</span></span>&gt;My Link&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>As a convenience you can also pass a domain instance to the <code>resource</code> attribute of the <code>link</code> tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;<span class="key">g</span>:link resource=<span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>book<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>&gt;My Link&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>This will automatically produce the correct link (in this case "/books/1" for an id of "1").</p>
</div>
<div class="paragraph">
<p>The case of nested resources is a little different as they typically required two identifiers (the id of the resource and the one it is nested within). For example given the nested resources:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>) {
  <span class="string"><span class="delimiter">&quot;</span><span class="content">/authors</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">author</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you wished to link to the <code>show</code> action of the <code>author</code> controller, you would write:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Results in /books/1/authors/2</span>
&lt;<span class="key">g</span>:link controller=<span class="string"><span class="delimiter">&quot;</span><span class="content">author</span><span class="delimiter">&quot;</span></span> action=<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span> method=<span class="string"><span class="delimiter">&quot;</span><span class="content">GET</span><span class="delimiter">&quot;</span></span> params=<span class="string"><span class="delimiter">&quot;</span><span class="content">[bookId:1]</span><span class="delimiter">&quot;</span></span> id=<span class="string"><span class="delimiter">&quot;</span><span class="content">2</span><span class="delimiter">&quot;</span></span>&gt;The Author&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>However, to make this more concise there is a <code>resource</code> attribute to the link tag which can be used instead:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Results in /books/1/authors/2</span>
&lt;<span class="key">g</span>:link resource=<span class="string"><span class="delimiter">&quot;</span><span class="content">book/author</span><span class="delimiter">&quot;</span></span> action=<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span> bookId=<span class="string"><span class="delimiter">&quot;</span><span class="content">1</span><span class="delimiter">&quot;</span></span> id=<span class="string"><span class="delimiter">&quot;</span><span class="content">2</span><span class="delimiter">&quot;</span></span>&gt;My Link&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The resource attribute accepts a path to the resource separated by a slash (in this case "book/author"). The attributes of the tag can be used to specify the necessary <code>bookId</code> parameter.</p>
</div>
</div>

<a name="7.4.2 Redirects In URL Mappings"><!-- Legacy link --></a>
<h2 id="redirectMappings">8.4.3 Redirects In URL Mappings</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/redirectMappings.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Since Grails 2.3, it is possible to define URL mappings which specify a redirect.
When a URL mapping specifies a redirect, any time that mapping matches an incoming
request, a redirect is initiated with information provided by the mapping.</p>
</div>
<div class="paragraph">
<p>When a URL mapping specifies a redirect the mapping must either supply a String
representing a URI to redirect to or must provide a Map representing the target
of the redirect.  That Map is structured just like the Map that may be passed
as an argument to the <code>redirect</code> method in a controller.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/viewBooks</span><span class="delimiter">&quot;</span></span>(<span class="key">redirect</span>: <span class="string"><span class="delimiter">'</span><span class="content">/books/list</span><span class="delimiter">'</span></span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">/viewAuthors</span><span class="delimiter">&quot;</span></span>(<span class="key">redirect</span>: [<span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">author</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">list</span><span class="delimiter">'</span></span>])
<span class="string"><span class="delimiter">&quot;</span><span class="content">/viewPublishers</span><span class="delimiter">&quot;</span></span>(<span class="key">redirect</span>: [<span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">publisher</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">list</span><span class="delimiter">'</span></span>, <span class="key">permanent</span>: <span class="predefined-constant">true</span>])</code></pre>
</div>
</div>
<div class="paragraph">
<p>Request parameters that were part of the original request will be included in the redirect.</p>
</div>

<a name="7.4.4 Embedded Variables"><!-- Legacy link --></a>
<h2 id="embeddedVariables">8.4.4 Embedded Variables</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/embeddedVariables.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="sect3">
<h4 id="_simple_variables">Simple Variables</h4>
<div class="paragraph">
<p>The previous section demonstrated how to map simple URLs with concrete "tokens". In URL mapping speak tokens are the sequence of characters between each slash, '/'. A concrete token is one which is well defined such as as <code>/product</code>. However, in many circumstances you don&#8217;t know what the value of a particular token will be until runtime. In this case you can use variable placeholders within the URL for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
  <span class="string"><span class="delimiter">&quot;</span><span class="content">/product/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case by embedding a $id variable as the second token Grails will automatically map the second token into a parameter (available via the <a href="../ref/Controllers/params.html">params</a> object) called <code>id</code>. For example given the URL <code>/product/MacBook</code>, the following code will render "MacBook" to the response:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ProductController</span> {
     <span class="keyword">def</span> <span class="function">index</span>() { render params.id }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can of course construct more complex examples of mappings. For example the traditional blog URL format could be mapped as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
   <span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>blog</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>year</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>month</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>day</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above mapping would let you do things like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/graemerocher/2007/01/10/my_funky_blog_entry</code></pre>
</div>
</div>
<div class="paragraph">
<p>The individual tokens in the URL would again be mapped into the <a href="../ref/Controllers/params.html">params</a> object with values available for <code>year</code>, <code>month</code>, <code>day</code>, <code>id</code> and so on.</p>
</div>
</div>
<div class="sect3">
<h4 id="_dynamic_controller_and_action_names">Dynamic Controller and Action Names</h4>
<div class="paragraph">
<p>Variables can also be used to dynamically construct the controller and action name. In fact the default Grails URL mappings use this technique:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>action</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span>()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here the name of the controller, action and id are implicitly obtained from the variables <code>controller</code>, <code>action</code> and <code>id</code> embedded within the URL.</p>
</div>
<div class="paragraph">
<p>You can also resolve the controller name and action name to execute dynamically using a closure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="delimiter">&quot;</span></span> {
        action = { params.goHere }
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_optional_variables">Optional Variables</h4>
<div class="paragraph">
<p>Another characteristic of the default mapping is the ability to append a ? at the end of a variable to make it an optional token. In a further example this technique could be applied to the blog URL mapping to have more flexible linking:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>blog</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>year</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>month</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>day</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With this mapping all of these URLs would match with only the relevant parameters being populated in the <a href="../ref/Controllers/params.html">params</a> object:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>/graemerocher/2007/01/10/my_funky_blog_entry
/graemerocher/2007/01/10
/graemerocher/2007/01
/graemerocher/2007
/graemerocher</pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_optional_file_extensions">Optional File Extensions</h4>
<div class="paragraph">
<p>If you wish to capture the extension of a particular path, then a special case mapping exists:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>action</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?(.</span><span class="inline"><span class="inline-delimiter">$</span>format</span><span class="content">)?</span><span class="delimiter">&quot;</span></span>()</code></pre>
</div>
</div>
<div class="paragraph">
<p>By adding the <code>(.$format)?</code> mapping you can access the file extension using the <code>response.format</code> property in a controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">index</span>() {
    render <span class="string"><span class="delimiter">&quot;</span><span class="content">extension is </span><span class="inline"><span class="inline-delimiter">${</span>response.format<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_arbitrary_variables">Arbitrary Variables</h4>
<div class="paragraph">
<p>You can also pass arbitrary parameters from the URL mapping into the controller by just setting them in the block passed to the mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/holiday/win</span><span class="delimiter">&quot;</span></span> {
     id = <span class="string"><span class="delimiter">&quot;</span><span class="content">Marrakech</span><span class="delimiter">&quot;</span></span>
     year = <span class="integer">2007</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This variables will be available within the <a href="../ref/Controllers/params.html">params</a> object passed to the controller.</p>
</div>
</div>
<div class="sect3">
<h4 id="_dynamically_resolved_variables">Dynamically Resolved Variables</h4>
<div class="paragraph">
<p>The hard coded arbitrary variables are useful, but sometimes you need to calculate the name of the variable based on runtime factors. This is also possible by assigning a block to the variable name:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/holiday/win</span><span class="delimiter">&quot;</span></span> {
     id = { params.id }
     isEligible = { session.user != <span class="predefined-constant">null</span> } <span class="comment">// must be logged in</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the above case the code within the blocks is resolved when the URL is actually matched and hence can be used in combination with all sorts of logic.</p>
</div>
</div>

<a name="7.4.5 Mapping to Views"><!-- Legacy link --></a>
<h2 id="mappingToViews">8.4.5 Mapping to Views</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/mappingToViews.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>You can resolve a URL to a view without a controller or action involved. For example to map the root URL <code>/</code> to a GSP at the location <code>grails-app/views/index.gsp</code> you could use:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/index</span><span class="delimiter">&quot;</span></span>)  <span class="comment">// map the root URL</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively if you need a view that is specific to a given controller you could use:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
   <span class="string"><span class="delimiter">&quot;</span><span class="content">/help</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">site</span><span class="delimiter">&quot;</span></span>, <span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">help</span><span class="delimiter">&quot;</span></span>) <span class="comment">// to a view for a controller</span>
}</code></pre>
</div>
</div>

<a name="7.4.6 Mapping to Response Codes"><!-- Legacy link --></a>
<h2 id="mappingToResponseCodes">8.4.6 Mapping to Response Codes</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/mappingToResponseCodes.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Grails also lets you map HTTP response codes to controllers, actions or views. Just use a method name that matches the response code you are interested in:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
   <span class="string"><span class="delimiter">&quot;</span><span class="content">403</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">forbidden</span><span class="delimiter">&quot;</span></span>)
   <span class="string"><span class="delimiter">&quot;</span><span class="content">404</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">notFound</span><span class="delimiter">&quot;</span></span>)
   <span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">serverError</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or you can specify custom error pages:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
   <span class="string"><span class="delimiter">&quot;</span><span class="content">403</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/forbidden</span><span class="delimiter">&quot;</span></span>)
   <span class="string"><span class="delimiter">&quot;</span><span class="content">404</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/notFound</span><span class="delimiter">&quot;</span></span>)
   <span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/serverError</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_declarative_error_handling">Declarative Error Handling</h4>
<div class="paragraph">
<p>In addition you can configure handlers for individual exceptions:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
   <span class="string"><span class="delimiter">&quot;</span><span class="content">403</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/forbidden</span><span class="delimiter">&quot;</span></span>)
   <span class="string"><span class="delimiter">&quot;</span><span class="content">404</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/notFound</span><span class="delimiter">&quot;</span></span>)
   <span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">illegalArgument</span><span class="delimiter">&quot;</span></span>,
         <span class="key">exception</span>: <span class="exception">IllegalArgumentException</span>)
   <span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">nullPointer</span><span class="delimiter">&quot;</span></span>,
         <span class="key">exception</span>: <span class="exception">NullPointerException</span>)
   <span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">customException</span><span class="delimiter">&quot;</span></span>,
         <span class="key">exception</span>: MyException)
   <span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/serverError</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With this configuration, an <code>IllegalArgumentException</code> will be handled by the <code>illegalArgument</code> action in <code>ErrorsController</code>, a <code>NullPointerException</code> will be handled by the <code>nullPointer</code> action, and a <code>MyException</code> will be handled by the <code>customException</code> action. Other exceptions will be handled by the catch-all rule and use the <code>/errors/serverError</code> view.</p>
</div>
<div class="paragraph">
<p>You can access the exception from your custom error handing view or controller action using the request&#8217;s <code>exception</code> attribute like so:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ErrorController</span> {
    <span class="keyword">def</span> <span class="function">handleError</span>() {
        <span class="keyword">def</span> exception = request.exception
        <span class="comment">// perform desired processing to handle the exception</span>
    }
}</code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
If your error-handling controller action throws an exception as well, you&#8217;ll end up with a <code>StackOverflowException</code>.
</td>
</tr>
</table>
</div>
</div>

<a name="7.4.7 Mapping to HTTP methods"><!-- Legacy link --></a>
<h2 id="mappingHTTP">8.4.7 Mapping to HTTP methods</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>URL mappings can also be configured to map based on the HTTP method (GET, POST, PUT or DELETE). This is very useful for RESTful APIs and for restricting mappings based on HTTP method.</p>
</div>
<div class="paragraph">
<p>As an example the following mappings provide a RESTful API URL mappings for the <code>ProductController</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
   <span class="string"><span class="delimiter">&quot;</span><span class="content">/product/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">update</span><span class="delimiter">&quot;</span></span>, <span class="key">method</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">PUT</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that if you specify a HTTP method other than GET in your URL mapping, you also have to specify it when creating the corresponding link by passing the <code>method</code> argument to <code>g:link</code> or <code>g:createLink</code> to get a link of the desired format.</p>
</div>

<a name="7.4.8 Mapping Wildcards"><!-- Legacy link --></a>
<h2 id="mappingWildcards">8.4.8 Mapping Wildcards</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/mappingWildcards.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Grails' URL mappings mechanism also supports wildcard mappings. For example consider the following mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/images/*.jpg</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">image</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This mapping will match all paths to images such as <code>/image/logo.jpg</code>. Of course you can achieve the same effect with a variable:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/images/</span><span class="inline"><span class="inline-delimiter">$</span>name</span><span class="content">.jpg</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">image</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>However, you can also use double wildcards to match more than one level below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/images/**.jpg</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">image</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this cases the mapping will match <code>/image/logo.jpg</code> as well as <code>/image/other/logo.jpg</code>. Even better you can use a double wildcard variable:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    <span class="comment">// will match /image/logo.jpg and /image/other/logo.jpg</span>
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/images/</span><span class="inline"><span class="inline-delimiter">$</span>name</span><span class="content">**.jpg</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">image</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case it will store the path matched by the wildcard inside a <code>name</code> parameter obtainable from the <a href="../ref/Controllers/params.html">params</a> object:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> name = params.name
println name <span class="comment">// prints &quot;logo&quot; or &quot;other/logo&quot;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>If you use wildcard URL mappings then you may want to exclude certain URIs from Grails' URL mapping process. To do this you can provide an <code>excludes</code> setting inside the <code>UrlMappings.groovy</code> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">UrlMappings</span> {
    <span class="directive">static</span> excludes = [<span class="string"><span class="delimiter">&quot;</span><span class="content">/images/*</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">/css/*</span><span class="delimiter">&quot;</span></span>]
    <span class="directive">static</span> mappings = {
        ...
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case Grails won&#8217;t attempt to match any URIs that start with <code>/images</code> or <code>/css</code>.</p>
</div>

<a name="7.4.9 Automatic Link Re-Writing"><!-- Legacy link --></a>
<h2 id="automaticLinkRewriting">8.4.9 Automatic Link Re-Writing</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/automaticLinkRewriting.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Another great feature of URL mappings is that they automatically customize the behaviour of the <a href="../ref/Tags/link.html">link</a> tag so that changing the mappings don&#8217;t require you to go and change all of your links.</p>
</div>
<div class="paragraph">
<p>This is done through a URL re-writing technique that reverse engineers the links from the URL mappings. So given a mapping such as the blog one from an earlier section:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
   <span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>blog</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>year</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>month</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>day</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you use the link tag as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:link</span> <span class="attribute-name">controller</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>
        <span class="attribute-name">params</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[blog:'fred', year:2007]</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
    My Blog
<span class="tag">&lt;/g:link&gt;</span>

<span class="tag">&lt;g:link</span> <span class="attribute-name">controller</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>
        <span class="attribute-name">params</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[blog:'fred', year:2007, month:10]</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
    My Blog - October 2007 Posts
<span class="tag">&lt;/g:link&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Grails will automatically re-write the URL in the correct format:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/fred/2007</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>My Blog<span class="tag">&lt;/a&gt;</span>
<span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/fred/2007/10</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>My Blog - October 2007 Posts<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>

<a name="7.4.10 Applying Constraints"><!-- Legacy link --></a>
<h2 id="applyingConstraints">8.4.10 Applying Constraints</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/applyingConstraints.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>URL Mappings also support Grails' unified <a href="validation.html#constraints">validation constraints</a> mechanism, which lets you further "constrain" how a URL is matched. For example, if we revisit the blog sample code from earlier, the mapping currently looks like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
   <span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>blog</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>year</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>month</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>day</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This allows URLs such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/graemerocher/2007/01/10/my_funky_blog_entry</code></pre>
</div>
</div>
<div class="paragraph">
<p>However, it would also allow:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/graemerocher/not_a_year/not_a_month/not_a_day/my_funky_blog_entry</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is problematic as it forces you to do some clever parsing in the controller code. Luckily, URL Mappings can be constrained to further validate the URL tokens:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>blog</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>year</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>month</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>day</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span> {
     controller = <span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span>
     action = <span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>
     constraints {
          year(<span class="key">matches</span>:<span class="regexp"><span class="delimiter">/</span><span class="char">\\</span><span class="char">\d</span><span class="content">{4}</span><span class="delimiter">/</span></span>)
          month(<span class="key">matches</span>:<span class="regexp"><span class="delimiter">/</span><span class="char">\\</span><span class="char">\d</span><span class="content">{2}</span><span class="delimiter">/</span></span>)
          day(<span class="key">matches</span>:<span class="regexp"><span class="delimiter">/</span><span class="char">\\</span><span class="char">\d</span><span class="content">{2}</span><span class="delimiter">/</span></span>)
     }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case the constraints ensure that the <code>year</code>, <code>month</code> and <code>day</code> parameters match a particular valid pattern thus relieving you of that burden later on.</p>
</div>

<a name="7.4.11 Named URL Mappings"><!-- Legacy link --></a>
<h2 id="namedMappings">8.4.11 Named URL Mappings</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/namedMappings.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>URL Mappings also support named mappings, that is mappings which have a name associated with them. The name may be used to refer to a specific mapping when links are generated.</p>
</div>
<div class="paragraph">
<p>The syntax for defining a named mapping is as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
   name &lt;mapping name&gt;: &lt;url pattern&gt; {
      <span class="comment">// ...</span>
   }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    name <span class="key">personList</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/showPeople</span><span class="delimiter">&quot;</span></span> {
        controller = <span class="string"><span class="delimiter">'</span><span class="content">person</span><span class="delimiter">'</span></span>
        action = <span class="string"><span class="delimiter">'</span><span class="content">list</span><span class="delimiter">'</span></span>
    }
    name <span class="key">accountDetails</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/details/</span><span class="inline"><span class="inline-delimiter">$</span>acctNumber</span><span class="delimiter">&quot;</span></span> {
        controller = <span class="string"><span class="delimiter">'</span><span class="content">product</span><span class="delimiter">'</span></span>
        action = <span class="string"><span class="delimiter">'</span><span class="content">accountDetails</span><span class="delimiter">'</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The mapping may be referenced in a link tag in a GSP.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:link</span> <span class="attribute-name">mapping</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">personList</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>List People<span class="tag">&lt;/g:link&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That would result in:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/showPeople</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>List People<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Parameters may be specified using the params attribute.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:link</span> <span class="attribute-name">mapping</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">accountDetails</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">params</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[acctNumber:'8675309']</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
    Show Account
<span class="tag">&lt;/g:link&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That would result in:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/details/8675309</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Show Account<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively you may reference a named mapping using the link namespace.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;link:personList&gt;</span>List People<span class="tag">&lt;/link:personList&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That would result in:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/showPeople</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>List People<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The link namespace approach allows parameters to be specified as attributes.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;link:accountDetails</span> <span class="attribute-name">acctNumber</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">8675309</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Show Account<span class="tag">&lt;/link:accountDetails&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That would result in:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/details/8675309</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Show Account<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>To specify attributes that should be applied to the generated <code>href</code>, specify a <code>Map</code> value to the <code>attrs</code> attribute.  These attributes will be applied directly to the href, not passed through to be used as request parameters.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;link:accountDetails</span> <span class="attribute-name">attrs</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[class: 'fancy']</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">acctNumber</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">8675309</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
    Show Account
<span class="tag">&lt;/link:accountDetails&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That would result in:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/details/8675309</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">fancy</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Show Account<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>


<h2 id="customizingUrlFormat">8.4.12 Customizing URL Formats</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/customizingUrlFormat.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>The default URL Mapping mechanism supports camel case names in the URLs.  The default URL for accessing an action named <code>addNumbers</code> in a controller named <code>MathHelperController</code> would be something like <code>/mathHelper/addNumbers</code>.  Grails allows for the customization of this pattern and provides an implementation which replaces the camel case convention with a hyphenated convention that would support URLs like <code>/math-helper/add-numbers</code>.  To enable hyphenated URLs assign a value of "hyphenated" to the <code>grails.web.url.converter</code> property in <code>grails-app/conf/application.groovy</code>.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.web.url.converter = <span class="string"><span class="delimiter">'</span><span class="content">hyphenated</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Arbitrary strategies may be plugged in by providing a class which implements the <a href="http://docs.grails.org/3.2.11/api/grails/web/UrlConverter.html">UrlConverter</a> interface and adding an instance of that class to the Spring application context with the bean name of <code>grails.web.UrlConverter.BEAN_NAME</code>.  If Grails finds a bean in the context with that name, it will be used as the default converter and there is no need to assign a value to the <code>grails.web.url.converter</code> config property.</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/com/myapplication/MyUrlConverterImpl.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.myapplication

<span class="type">class</span> <span class="class">MyUrlConverterImpl</span> <span class="directive">implements</span> grails.web.UrlConverter {

    <span class="predefined-type">String</span> toUrlElement(<span class="predefined-type">String</span> propertyOrClassName) {
        <span class="comment">// return some representation of a property or class name that should be used in URLs...</span>
    }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/spring/resources.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
    <span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>grails.web.UrlConverter.BEAN_NAME<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>(com.myapplication.MyUrlConverterImpl)
}</code></pre>
</div>
</div>


<h2 id="namespacedControllers">8.4.13 Namespaced Controllers</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/urlmappings/namespacedControllers.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>If an application defines multiple controllers with the same name
in different packages, the controllers must be defined in a
namespace.  The way to define a namespace for a controller is to
define a static property named <code>namespace</code> in the controller and
assign a String to the property that represents the namespace.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/com/app/reporting/AdminController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.app.reporting

<span class="type">class</span> <span class="class">AdminController</span> {

    <span class="directive">static</span> namespace = <span class="string"><span class="delimiter">'</span><span class="content">reports</span><span class="delimiter">'</span></span>

    <span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/com/app/security/AdminController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.app.security

<span class="type">class</span> <span class="class">AdminController</span> {

    <span class="directive">static</span> namespace = <span class="string"><span class="delimiter">'</span><span class="content">users</span><span class="delimiter">'</span></span>

    <span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When defining url mappings which should be associated with a namespaced
controller, the <code>namespace</code> variable needs to be part of the URL mapping.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/UrlMappings.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">UrlMappings</span> {

    <span class="directive">static</span> mappings = {
        <span class="string"><span class="delimiter">'</span><span class="content">/userAdmin</span><span class="delimiter">'</span></span> {
            controller = <span class="string"><span class="delimiter">'</span><span class="content">admin</span><span class="delimiter">'</span></span>
            namespace = <span class="string"><span class="delimiter">'</span><span class="content">users</span><span class="delimiter">'</span></span>
        }

        <span class="string"><span class="delimiter">'</span><span class="content">/reportAdmin</span><span class="delimiter">'</span></span> {
            controller = <span class="string"><span class="delimiter">'</span><span class="content">admin</span><span class="delimiter">'</span></span>
            namespace = <span class="string"><span class="delimiter">'</span><span class="content">reports</span><span class="delimiter">'</span></span>
        }

        <span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>namespace</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>action</span><span class="content">?</span><span class="delimiter">&quot;</span></span>()
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Reverse URL mappings also require that the <code>namespace</code> be specified.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;<span class="key">g</span>:link controller=<span class="string"><span class="delimiter">&quot;</span><span class="content">admin</span><span class="delimiter">&quot;</span></span> namespace=<span class="string"><span class="delimiter">&quot;</span><span class="content">reports</span><span class="delimiter">&quot;</span></span>&gt;Click For Report Admin&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span><span class="error">
</span>&lt;<span class="key">g</span>:link controller=<span class="string"><span class="delimiter">&quot;</span><span class="content">admin</span><span class="delimiter">&quot;</span></span> namespace=<span class="string"><span class="delimiter">&quot;</span><span class="content">users</span><span class="delimiter">&quot;</span></span>&gt;Click For User Admin&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>When resolving a URL mapping (forward or reverse) to a namespaced controller,
a mapping will only match if the <code>namespace</code> has been provided.  If
the application provides several controllers with the same name in different
packages, at most 1 of them may be defined without a <code>namespace</code> property.  If
there are multiple controllers with the same name that do not define a
<code>namespace</code> property, the framework will not know how to distinguish between
them for forward or reverse mapping resolutions.</p>
</div>
<div class="paragraph">
<p>It is allowed for an application to use a plugin which provides a controller
with the same name as a controller provided by the application and for neither
of the controllers to define a <code>namespace</code> property as long as the
controllers are in separate packages.  For example, an application
may include a controller named <code>com.accounting.ReportingController</code>
and the application may use a plugin which provides a controller
named <code>com.humanresources.ReportingController</code>.  The only issue
with that is the URL mapping for the controller provided by the
plugin needs to be explicit in specifying that the mapping applies
to the <code>ReportingController</code> which is provided by the plugin.</p>
</div>
<div class="paragraph">
<p>See the following example.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/accountingReports</span><span class="delimiter">&quot;</span></span> {
        controller = <span class="string"><span class="delimiter">&quot;</span><span class="content">reporting</span><span class="delimiter">&quot;</span></span>
    }
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/humanResourceReports</span><span class="delimiter">&quot;</span></span> {
        controller = <span class="string"><span class="delimiter">&quot;</span><span class="content">reporting</span><span class="delimiter">&quot;</span></span>
        plugin = <span class="string"><span class="delimiter">&quot;</span><span class="content">humanResources</span><span class="delimiter">&quot;</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With that mapping in place, a request to <code>/accountingReports</code> will
be handled by the <code>ReportingController</code> which is defined in the
application.  A request to <code>/humanResourceReports</code> will be handled
by the <code>ReportingController</code> which is provided by the <code>humanResources</code>
plugin.</p>
</div>
<div class="paragraph">
<p>There could be any number of <code>ReportingController</code> controllers provided
by any number of plugins but no plugin may provide more than one
<code>ReportingController</code> even if they are defined in separate packages.</p>
</div>
<div class="paragraph">
<p>Assigning a value to the <code>plugin</code> variable in the mapping is only
required if there are multiple controllers with the same name
available at runtime provided by the application and/or plugins.
If the <code>humanResources</code> plugin provides a <code>ReportingController</code> and
there is no other <code>ReportingController</code> available at runtime, the
following mapping would work.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
    <span class="string"><span class="delimiter">&quot;</span><span class="content">/humanResourceReports</span><span class="delimiter">&quot;</span></span> {
        controller = <span class="string"><span class="delimiter">&quot;</span><span class="content">reporting</span><span class="delimiter">&quot;</span></span>
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>It is best practice to be explicit about the fact that the controller
is being provided by a plugin.</p>
</div>


<h2 id="cors">8.5 CORS</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/cors.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Spring Boot provides CORS support out of the box, but it is difficult to configure in a Grails application due to the way UrlMappings are used instead of annotations that define URLs. Starting with Grails 3.2.1, we have added a way to configure CORS that makes sense in a Grails application.</p>
</div>
<div class="paragraph">
<p>Once enabled, the default setting is "wide open".</p>
</div>
<div class="listingblock">
<div class="title">application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
    <span class="key">cors</span>:
        <span class="key">enabled</span>: <span class="string"><span class="content">true</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That will produce a mapping to all urls <code>/**</code> with:</p>
</div>
<table class="tableblock frame-all grid-all" style="width: 40%;">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedOrigins</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['*']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedMethods</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['*']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedHeaders</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['*']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">exposedHeaders</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>null</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">maxAge</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>1800</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowCredentials</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">true</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>Some of these settings come directly from Spring Boot and can change in future versions. See <a href="https://docs.spring.io/spring/docs/current/javadoc-api//org/springframework/web/cors/CorsConfiguration.html#applyPermitDefaultValues--" class="bare">https://docs.spring.io/spring/docs/current/javadoc-api//org/springframework/web/cors/CorsConfiguration.html#applyPermitDefaultValues--</a></p>
</div>
<div class="paragraph">
<p>All of those settings can be easily overridden.</p>
</div>
<div class="listingblock">
<div class="title">application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
    <span class="key">cors</span>:
        <span class="key">enabled</span>: <span class="string"><span class="content">true</span></span>
        <span class="key">allowedOrigins</span>:
            - <span class="string"><span class="content">http://localhost:5000</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>In the example above, the <code>allowedOrigins</code> setting will replace <code>[*]</code>.</p>
</div>
<div class="paragraph">
<p>You can also configure different URLs.</p>
</div>
<div class="listingblock">
<div class="title">application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
    <span class="key">cors</span>:
        <span class="key">enabled</span>: <span class="string"><span class="content">true</span></span>
        <span class="key">allowedHeaders</span>:
            - <span class="string"><span class="content">Content-Type</span></span>
        <span class="key">mappings</span>:
            <span class="error">/api/**</span>:
                <span class="key">allowedOrigins</span>:
                    - <span class="string"><span class="content">http://localhost:5000</span></span>
                <span class="comment"># Other configurations not specified default to the global config</span></code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Specifying at least one mapping will disable the creation of the global mapping (<code>/**</code>). If you wish to keep that setting, you should specify it along with your other mappings.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The settings above will produce a single mapping of <code>/api/**</code> with the following settings:</p>
</div>
<table class="tableblock frame-all grid-all" style="width: 40%;">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedOrigins</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['http://localhost:5000']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedMethods</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['*']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedHeaders</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['Content-Type']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">exposedHeaders</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>null</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">maxAge</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>1800</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowCredentials</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">true</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>If you don&#8217;t wish to override any of the default settings, but only want to specify URLs, you can do so like this example:</p>
</div>
<div class="listingblock">
<div class="title">application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
    <span class="key">cors</span>:
        <span class="key">enabled</span>: <span class="string"><span class="content">true</span></span>
        <span class="key">mappings</span>:
            <span class="error">/api/**</span>: <span class="error">inherit</span></code></pre>
</div>
</div>

<a name="7.1.5 Controller Interceptors"><!-- Legacy link --></a>
<h2 id="interceptors">8.6 Interceptors</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/interceptors.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Grails provides standalone Interceptors using the <a href="../ref/Command%20Line/create-interceptor.html">create-interceptor</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-interceptor MyInterceptor</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above command will create an Interceptor in the <code>grails-app/controllers</code> directory with the following default contents:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">MyInterceptor</span> {

  <span class="type">boolean</span> before() { <span class="predefined-constant">true</span> }

  <span class="type">boolean</span> after() { <span class="predefined-constant">true</span> }

  <span class="type">void</span> afterView() {
    <span class="comment">// no-op</span>
  }

}</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_interceptors_vs_filters">Interceptors vs Filters</h4>
<div class="paragraph">
<p>In versions of Grails prior to Grails 3.0, Grails supported the notion of filters. These are still supported for backwards compatibility but are considered deprecated.</p>
</div>
<div class="paragraph">
<p>The new interceptors concept in Grails 3.0 is superior in a number of ways, most significantly interceptors can use Groovy&#8217;s <code>CompileStatic</code> annotation to optimize performance (something which is often critical as interceptors can be executed for every request.)</p>
</div>
</div>


<h2 id="definingInterceptors">8.6.1 Defining Interceptors</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/interceptors/definingInterceptors.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>By default interceptors will match the controllers with the same name. For example if you have an interceptor called <code>BookInterceptor</code> then all requests to the actions of the <code>BookController</code> will trigger the interceptor.</p>
</div>
<div class="paragraph">
<p>An <code>Interceptor</code> implements the <a href="http://docs.grails.org/3.2.11/api/grails/artefact/Interceptor.html">Interceptor</a> trait and provides 3 methods that can be used to intercept requests:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">/**
 * Executed before a matched action
 *
 * @return Whether the action should continue and execute
 */</span>
<span class="type">boolean</span> before() { <span class="predefined-constant">true</span> }

<span class="comment">/**
 * Executed after the action executes but prior to view rendering
 *
 * @return True if view rendering should continue, false otherwise
 */</span>
<span class="type">boolean</span> after() { <span class="predefined-constant">true</span> }

<span class="comment">/**
 * Executed after view rendering completes
 */</span>
<span class="type">void</span> afterView() {}</code></pre>
</div>
</div>
<div class="paragraph">
<p>As described above the <code>before</code> method is executed prior to an action and can cancel the execution of the action by returning <code>false</code>.</p>
</div>
<div class="paragraph">
<p>The <code>after</code> method is executed after an action executes and can halt view rendering if it returns false. The <code>after</code> method can also modify the view or model using the <code>view</code> and <code>model</code> properties respectively:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">boolean</span> after() {
  model.foo = <span class="string"><span class="delimiter">&quot;</span><span class="content">bar</span><span class="delimiter">&quot;</span></span> <span class="comment">// add a new model attribute called 'foo'</span>
  view = <span class="string"><span class="delimiter">'</span><span class="content">alternate</span><span class="delimiter">'</span></span> <span class="comment">// render a different view called 'alternate'</span>
  <span class="predefined-constant">true</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>afterView</code> method is executed after view rendering completes. If an exception occurs, the exception is available using the <code>throwable</code> property of the <a href="http://docs.grails.org/3.2.11/api/grails/artefact/Interceptor.html">Interceptor</a> trait.</p>
</div>


<h2 id="interceptorMatching">8.6.2 Matching Requests with Inteceptors</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/interceptors/interceptorMatching.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>As mention in the previous section, by default an interceptor will match only requests to the associated controller by convention. However you can configure the interceptor to match any request using the <code>match</code> or <code>matchAll</code> methods defined in the <a href="http://docs.grails.org/3.2.11/api/grails/artefact/Interceptor.html">Interceptor API</a>.</p>
</div>
<div class="paragraph">
<p>The matching methods return a <a href="http://docs.grails.org/3.2.11/api/grails/interceptors/Matcher.html">Matcher</a> instance which can be used to configure how the interceptor matches the request.</p>
</div>
<div class="paragraph">
<p>For example the following interceptor will match all requests except those to the <code>login</code> controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthInterceptor</span> {
  AuthInterceptor() {
    matchAll()
    .excludes(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">login</span><span class="delimiter">&quot;</span></span>)
  }

  <span class="type">boolean</span> before() {
    <span class="comment">// perform authentication</span>
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also perform matching using named argument:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">LoggingInterceptor</span> {
  LoggingInterceptor() {
    match(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>) <span class="comment">// using strings</span>
    match(<span class="key">controller</span>: ~<span class="regexp"><span class="delimiter">/</span><span class="content">(author|publisher)</span><span class="delimiter">/</span></span>) <span class="comment">// using regex</span>
  }

  <span class="type">boolean</span> before() {
    ...
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can use any number of matchers defined in your interceptor. They will be executed in the order in which they have been defined. For example the above interceptor will match for all of the following:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>when the <code>show</code> action of <code>BookController</code> is called</p>
</li>
<li>
<p>when <code>AuthorController</code> or <code>PublisherController</code> is called</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>All named arguments except for <code>uri</code> accept either a String or a Regex expression. The <code>uri</code> argument supports a String path that is compatible with Spring&#8217;s <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html">AntPathMatcher</a>.  The possible named arguments are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>namespace</code> - The namespace of the controller</p>
</li>
<li>
<p><code>controller</code> - The name of the controller</p>
</li>
<li>
<p><code>action</code> - The name of the action</p>
</li>
<li>
<p><code>method</code> - The HTTP method</p>
</li>
<li>
<p><code>uri</code> - The URI of the request. If this argument is used then all other arguments will be ignored and only this will be used.</p>
</li>
</ul>
</div>


<h2 id="interceptorOrdering">8.6.3 Ordering Interceptor Execution</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/interceptors/interceptorOrdering.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Interceptors can be ordered by defining an <code>order</code> property that defines a priority.</p>
</div>
<div class="paragraph">
<p>For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthInterceptor</span> {

  <span class="type">int</span> order = HIGHEST_PRECEDENCE

  ...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The default value of the <code>order</code> property is 0.  Interceptor execution order is determined by sorting the <code>order</code> property in an ascending direction and executing the lowest numerically ordered interceptor first.</p>
</div>
<div class="paragraph">
<p>The values <code>HIGHEST_PRECEDENCE</code> and <code>LOWEST_PRECEDENCE</code> can be used to define filters that should should run first or last respectively.</p>
</div>
<div class="paragraph">
<p>Note that if you write an interceptor that is to be used by others it is better increment or decrement the <code>HIGHEST_PRECEDENCE</code> and <code>LOWEST_PRECEDENCE</code> to allow other interceptors to be inserted before or after the interceptor you are authoring:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">int</span> order = HIGHEST_PRECEDENCE + <span class="integer">50</span>

<span class="comment">// or</span>

<span class="type">int</span> order = LOWEST_PRECEDENCE - <span class="integer">50</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>To find out the computed order of interceptors you can add a debug logger to <code>logback.groovy</code> as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">logger <span class="string"><span class="delimiter">'</span><span class="content">grails.artefact.Interceptor</span><span class="delimiter">'</span></span>, DEBUG, [<span class="string"><span class="delimiter">'</span><span class="content">STDOUT</span><span class="delimiter">'</span></span>], <span class="predefined-constant">false</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>You can override any interceptors default order by using bean override configuration in <code>grails-app/conf/application.yml</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">beans</span>:
  <span class="key">authInterceptor</span>:
    <span class="key">order</span>: <span class="integer">50</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Or in <code>grails-app/conf/application.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans {
  authInterceptor {
    order = <span class="integer">50</span>
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Thus giving you complete control over interceptor execution order.</p>
</div>

<a name="7.8 Content Negotiation"><!-- Legacy link --></a>
<h2 id="contentNegotiation">8.7 Content Negotiation</h2>

<div class='contribute-btn'>
    <button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.2.x/src/en/guide/theWebLayer/contentNegotiation.adoc"'>
        <i class='fa fa-pencil-square-o'></i> Improve this doc
    </button>
</div>


<div class="paragraph">
<p>Grails has built in support for <a href="http://en.wikipedia.org/wiki/Content_negotiation">Content negotiation</a> using either the HTTP <code>Accept</code> header, an explicit format request parameter or the extension of a mapped URI.</p>
</div>
<div class="sect3">
<h4 id="_configuring_mime_types">Configuring Mime Types</h4>
<div class="paragraph">
<p>Before you can start dealing with content negotiation you need to tell Grails what content types you wish to support. By default Grails comes configured with a number of different content types within <code>grails-app/conf/application.yml</code> using the <code>grails.mime.types</code> setting:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
    <span class="key">mime</span>:
        <span class="key">types</span>:
            <span class="key">all</span>: <span class="string"><span class="content">'*/*'</span></span>
            <span class="key">atom</span>: <span class="string"><span class="content">application/atom+xml</span></span>
            <span class="key">css</span>: <span class="string"><span class="content">text/css</span></span>
            <span class="key">csv</span>: <span class="string"><span class="content">text/csv</span></span>
            <span class="key">form</span>: <span class="string"><span class="content">application/x-www-form-urlencoded</span></span>
            <span class="key">html</span>:
              - <span class="string"><span class="content">text/html</span></span>
              - <span class="string"><span class="content">application/xhtml+xml</span></span>
            <span class="key">js</span>: <span class="string"><span class="content">text/javascript</span></span>
            <span class="key">json</span>:
              - <span class="string"><span class="content">application/json</span></span>
              - <span class="string"><span class="content">text/json</span></span>
            <span class="key">multipartForm</span>: <span class="string"><span class="content">multipart/form-data</span></span>
            <span class="key">rss</span>: <span class="string"><span class="content">application/rss+xml</span></span>
            <span class="key">text</span>: <span class="string"><span class="content">text/plain</span></span>
            <span class="key">hal</span>:
              - <span class="string"><span class="content">application/hal+json</span></span>
              - <span class="string"><span class="content">application/hal+xml</span></span>
            <span class="key">xml</span>:
              - <span class="string"><span class="content">text/xml</span></span>
              - <span class="string"><span class="content">application/xml</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The setting can also be done in <code>grails-app/conf/application.groovy</code> as shown below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.mime.types = [ <span class="comment">// the first one is the default format</span>
    <span class="key">all</span>:           <span class="string"><span class="delimiter">'</span><span class="content">*/*</span><span class="delimiter">'</span></span>, <span class="comment">// 'all' maps to '*' or the first available format in withFormat</span>
    <span class="key">atom</span>:          <span class="string"><span class="delimiter">'</span><span class="content">application/atom+xml</span><span class="delimiter">'</span></span>,
    <span class="key">css</span>:           <span class="string"><span class="delimiter">'</span><span class="content">text/css</span><span class="delimiter">'</span></span>,
    <span class="key">csv</span>:           <span class="string"><span class="delimiter">'</span><span class="content">text/csv</span><span class="delimiter">'</span></span>,
    <span class="key">form</span>:          <span class="string"><span class="delimiter">'</span><span class="content">application/x-www-form-urlencoded</span><span class="delimiter">'</span></span>,
    <span class="key">html</span>:          [<span class="string"><span class="delimiter">'</span><span class="content">text/html</span><span class="delimiter">'</span></span>,<span class="string"><span class="delimiter">'</span><span class="content">application/xhtml+xml</span><span class="delimiter">'</span></span>],
    <span class="key">js</span>:            <span class="string"><span class="delimiter">'</span><span class="content">text/javascript</span><span class="delimiter">'</span></span>,
    <span class="key">json</span>:          [<span class="string"><span class="delimiter">'</span><span class="content">application/json</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">text/json</span><span class="delimiter">'</span></span>],
    <span class="key">multipartForm</span>: <span class="string"><span class="delimiter">'</span><span class="content">multipart/form-data</span><span class="delimiter">'</span></span>,
    <span class="key">rss</span>:           <span class="string"><span class="delimiter">'</span><span class="content">application/rss+xml</span><span class="delimiter">'</span></span>,
    <span class="key">text</span>:          <span class="string"><span class="delimiter">'</span><span class="content">text/plain</span><span class="delimiter">'</span></span>,
    <span class="key">hal</span>:           [<span class="string"><span class="delimiter">'</span><span class="content">application/hal+json</span><span class="delimiter">'</span></span>,<span class="string"><span class="delimiter">'</span><span class="content">application/hal+xml</span><span class="delimiter">'</span></span>],
    <span class="key">xml</span>:           [<span class="string"><span class="delimiter">'</span><span class="content">text/xml</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">application/xml</span><span class="delimiter">'</span></span>]
]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above bit of configuration allows Grails to detect to format of a request containing either the 'text/xml' or 'application/xml' media types as simply 'xml'. You can add your own types by simply adding new entries into the map.
The first one is the default format.</p>
</div>
</div>
<div class="sect3">
<h4 id="_content_negotiation_using_the_format_request_parameter">Content Negotiation using the format Request Parameter</h4>
<div class="paragraph">
<p>Let&#8217;s say a controller action can return a resource in a variety of formats: HTML, XML, and JSON. What format will the client get? The easiest and most reliable way for the client to control this is through a <code>format</code> URL parameter.</p>
</div>
<div class="paragraph">
<p>So if you, as a browser or some other client, want a resource as XML, you can use a URL like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>http://my.domain.org/books?format=xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>The result of this on the server side is a <code>format</code> property on the <code>response</code> object with the value <code>xml</code> .</p>
</div>
<div class="paragraph">
<p>You can also define this parameter in the <a href="theWebLayer.html#urlmappings">URL Mappings</a> definition:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/book/list</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span>) {
    format = <span class="string"><span class="delimiter">&quot;</span><span class="content">xml</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You could code your controller action to return XML based on this property, but you can also make use of the controller-specific <code>withFormat()</code> method:</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
This example requires the addition of the <code>org.grails.plugins:grails-plugin-converters</code> plugin
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.converters.JSON</span>
<span class="keyword">import</span> <span class="include">grails.converters.XML</span>

<span class="type">class</span> <span class="class">BookController</span> {

    <span class="keyword">def</span> <span class="function">list</span>() {
        <span class="keyword">def</span> books = <span class="predefined-type">Book</span>.list()

        withFormat {
            html <span class="key">bookList</span>: books
            json { render books <span class="keyword">as</span> JSON }
            xml { render books <span class="keyword">as</span> XML }
            <span class="string"><span class="delimiter">'</span><span class="content">*</span><span class="delimiter">'</span></span> { render books <span class="keyword">as</span> JSON }
        }
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example, Grails will only execute the block inside <code>withFormat()</code> that matches the requested content type. So if the preferred format is <code>html</code> then Grails will execute the <code>html()</code> call only. Each 'block' can either be a map model for the corresponding view (as we are doing for 'html' in the above example) or a closure. The closure can contain any standard action code, for example it can return a model or render content directly.</p>
</div>
<div class="paragraph">
<p>When no format matches explicitly, a <code>*</code> (wildcard) block can be used to handle all other formats.</p>
</div>
<div class="paragraph">
<p>There is a special format, "all", that is handled differently from the explicit formats. If "all" is specified (normally this happens through the Accept header - see below), then the first block of <code>withFormat()</code> is executed when there isn&#8217;t a <code>*</code> (wildcard) block available.</p>
</div>
<div class="paragraph">
<p>You should not add an explicit "all" block. In this example, a format of "all" will trigger the <code>html</code> handler (<code>html</code> is the first block and there is no <code>*</code> block).</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">withFormat {
    html <span class="key">bookList</span>: books
    json { render books <span class="keyword">as</span> JSON }
    xml { render books <span class="keyword">as</span> XML }
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
When using <a href="../ref/Controllers/withFormat.html">withFormat</a> make sure it is the last call in your controller action as the return value of the <code>withFormat</code> method is used by the action to dictate what happens next.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_using_the_accept_header">Using the Accept header</h4>
<div class="paragraph">
<p>Every incoming HTTP request has a special <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">Accept</a> header that defines what media types (or mime types) a client can "accept". In older browsers this is typically:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>*/*</code></pre>
</div>
</div>
<div class="paragraph">
<p>which simply means anything. However, newer browsers send more interesting values such as this one sent by Firefox:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, \
    text/plain;q=0.8, image/png, */*;q=0.5</code></pre>
</div>
</div>
<div class="paragraph">
<p>This particular accept header is unhelpful because it indicates that XML is the preferred response format whereas the user is really expecting HTML. That&#8217;s why Grails ignores the accept header by default for browsers. However, non-browser clients are typically more specific in their requirements and can send accept headers such as</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">application/json</code></pre>
</div>
</div>
<div class="paragraph">
<p>As mentioned the default configuration in Grails is to ignore the accept header for browsers. This is done by the configuration setting <code>grails.mime.disable.accept.header.userAgents</code>, which is configured to detect the major rendering engines and ignore their ACCEPT headers. This allows Grails' content negotiation to continue to work for non-browser clients:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.mime.disable.accept.header.userAgents = [<span class="string"><span class="delimiter">'</span><span class="content">Gecko</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">WebKit</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">Presto</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">Trident</span><span class="delimiter">'</span></span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>For example, if it sees the accept header above ('application/json') it will set <code>format</code> to <code>json</code> as you&#8217;d expect. And of course this works with the <code>withFormat()</code> method in just the same way as when the <code>format</code> URL parameter is set (although the URL parameter takes precedence).</p>
</div>
<div class="paragraph">
<p>An accept header of '*/\*' results in a value of <code>all</code> for the <code>format</code> property.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
If the accept header is used but contains no registered content types, Grails will assume a broken browser is making the request and will set the HTML format - note that this is different from how the other content negotiation modes work as those would activate the "all" format!
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_request_format_vs_response_format">Request format vs. Response format</h4>
<div class="paragraph">
<p>As of Grails 2.0, there is a separate notion of the <em>request</em> format and the <em>response</em> format. The request format is dictated by the <code>CONTENT_TYPE</code> header and is typically used to detect if the incoming request can be parsed into XML or JSON, whilst the response format uses the file extension, format parameter or ACCEPT header to attempt to deliver an appropriate response to the client.</p>
</div>
<div class="paragraph">
<p>The <a href="../ref/Controllers/withFormat.html">withFormat</a> available on controllers deals specifically with the response format. If you wish to add logic that deals with the request format then you can do so using a separate <code>withFormat</code> method available on the request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">request.withFormat {
    xml {
        <span class="comment">// read XML</span>
    }
    json {
        <span class="comment">// read JSON</span>
    }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_content_negotiation_with_uri_extensions">Content Negotiation with URI Extensions</h4>
<div class="paragraph">
<p>Grails also supports content negotiation using URI extensions. For example given the following URI:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/book/list.xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>This works as a result of the default URL Mapping definition which is:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>action</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?(.</span><span class="inline"><span class="inline-delimiter">$</span>format</span><span class="content">)?</span><span class="delimiter">&quot;</span></span>{</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note the inclusion of the <code>format</code> variable in the path. If you do not wish to use content negotiation via the file extension then simply remove this part of the URL mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>action</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span>{</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_content_negotiation">Testing Content Negotiation</h4>
<div class="paragraph">
<p>To test content negotiation in a unit or integration test (see the section on <a href="testing.html">Testing</a>) you can either manipulate the incoming request headers:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">void</span> testJavascriptOutput() {
    <span class="keyword">def</span> controller = <span class="keyword">new</span> TestController()
    controller.request.addHeader <span class="string"><span class="delimiter">&quot;</span><span class="content">Accept</span><span class="delimiter">&quot;</span></span>,
              <span class="string"><span class="delimiter">&quot;</span><span class="content">text/javascript, text/html, application/xml, text/xml, */*</span><span class="delimiter">&quot;</span></span>

    controller.testAction()
    assertEquals <span class="string"><span class="delimiter">&quot;</span><span class="content">alert('hello')</span><span class="delimiter">&quot;</span></span>, controller.response.contentAsString
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or you can set the format parameter to achieve a similar effect:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">void</span> testJavascriptOutput() {
    <span class="keyword">def</span> controller = <span class="keyword">new</span> TestController()
    controller.params.format = <span class="string"><span class="delimiter">'</span><span class="content">js</span><span class="delimiter">'</span></span>

    controller.testAction()
    assertEquals <span class="string"><span class="delimiter">&quot;</span><span class="content">alert('hello')</span><span class="delimiter">&quot;</span></span>, controller.response.contentAsString
}</code></pre>
</div>
</div>
</div>


                <div style="clear:both;margin-top:15px;"></div>
                
                    <div class="toc-item prev-left"><a href="../guide/GORM.html">&lt;&lt; <strong>7</strong><span>Object Relational Mapping (GORM)</span></a></div>
                
                    <div class="toc-item next-right"><a href="../guide/traits.html"><strong>9</strong><span>Traits</span> >></a></div>
                
                <div style="clear:both"></div>
            </div>
        </td>
        <td id="col2">
            <div class="local clearfix">
                <div class="local-title">
                    <a href="../guide/index.html" target="mainFrame">Quick Reference</a>
                    <span class="toggle">(<a href="#" onclick="localToggle(); return false;">hide</a>)</span>
                </div>
                <div class="menu">
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Command Line</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Command%20Line/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/bug-report.html">bug-report</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/clean.html">clean</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/compile.html">compile</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/console.html">console</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-app.html">create-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-command.html">create-command</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-controller.html">create-controller</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-domain-class.html">create-domain-class</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-functional-test.html">create-functional-test</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-hibernate-cfg-xml.html">create-hibernate-cfg-xml</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-integration-test.html">create-integration-test</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-interceptor.html">create-interceptor</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-plugin.html">create-plugin</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-profile.html">create-profile</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-script.html">create-script</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-service.html">create-service</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-taglib.html">create-taglib</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-unit-test.html">create-unit-test</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/dependency-report.html">dependency-report</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/docs.html">docs</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/generate-all.html">generate-all</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/generate-controller.html">generate-controller</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/generate-views.html">generate-views</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/help.html">help</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/install-templates.html">install-templates</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/list-plugins.html">list-plugins</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/list-profiles.html">list-profiles</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/package-plugin.html">package-plugin</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/package.html">package</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/plugin-info.html">plugin-info</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/profile-info.html">profile-info</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/run-app.html">run-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/run-command.html">run-command</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/run-script.html">run-script</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/schema-export.html">schema-export</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/shell.html">shell</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/stats.html">stats</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/stop-app.html">stop-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/test-app.html">test-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/war.html">war</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Constraints</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Constraints/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Constraints/attributes.html">attributes</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/bindable.html">bindable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/blank.html">blank</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/creditCard.html">creditCard</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/email.html">email</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/inList.html">inList</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/matches.html">matches</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/max.html">max</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/maxSize.html">maxSize</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/min.html">min</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/minSize.html">minSize</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/notEqual.html">notEqual</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/nullable.html">nullable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/range.html">range</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/scale.html">scale</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/size.html">size</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/unique.html">unique</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/url.html">url</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/validator.html">validator</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/widget.html">widget</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Controllers</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Controllers/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Controllers/actionName.html">actionName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/allowedMethods.html">allowedMethods</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/bindData.html">bindData</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/chain.html">chain</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/controllerName.html">controllerName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/defaultAction.html">defaultAction</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/errors.html">errors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/flash.html">flash</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/forward.html">forward</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/grailsApplication.html">grailsApplication</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/hasErrors.html">hasErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/namespace.html">namespace</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/params.html">params</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/redirect.html">redirect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/render.html">render</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/request.html">request</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/respond.html">respond</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/response.html">response</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/responseFormats.html">responseFormats</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/scope.html">scope</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/servletContext.html">servletContext</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/session.html">session</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/withForm.html">withForm</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/withFormat.html">withFormat</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Database Mapping</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Database%20Mapping/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/autoImport.html">autoImport</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/autoTimestamp.html">autoTimestamp</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/batchSize.html">batchSize</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/cache.html">cache</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/cascade.html">cascade</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/column.html">column</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/comment.html">comment</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/discriminator.html">discriminator</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/dynamicInsert.html">dynamicInsert</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/dynamicUpdate.html">dynamicUpdate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/fetch.html">fetch</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/id.html">id</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/ignoreNotFound.html">ignoreNotFound</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/indexColumn.html">indexColumn</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/insertable.html">insertable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/joinTable.html">joinTable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/lazy.html">lazy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/order.html">order</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/sort.html">sort</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/table.html">table</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/type.html">type</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/updateable.html">updateable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/version.html">version</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Domain Classes</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Domain%20Classes/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/addTo.html">addTo</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/attach.html">attach</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/belongsTo.html">belongsTo</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/clearErrors.html">clearErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/constraints.html">constraints</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/count.html">count</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/countBy.html">countBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/createCriteria.html">createCriteria</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/delete.html">delete</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/discard.html">discard</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/embedded.html">embedded</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/errors.html">errors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/executeQuery.html">executeQuery</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/executeUpdate.html">executeUpdate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/exists.html">exists</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/fetchMode.html">fetchMode</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/find.html">find</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findAll.html">findAll</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findAllBy.html">findAllBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findAllWhere.html">findAllWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findBy.html">findBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrCreateBy.html">findOrCreateBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrCreateWhere.html">findOrCreateWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrSaveBy.html">findOrSaveBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrSaveWhere.html">findOrSaveWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findWhere.html">findWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/first.html">first</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/get.html">get</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/getAll.html">getAll</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/getDirtyPropertyNames.html">getDirtyPropertyNames</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/getPersistentValue.html">getPersistentValue</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/hasErrors.html">hasErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/hasMany.html">hasMany</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/hasOne.html">hasOne</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/ident.html">ident</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/instanceOf.html">instanceOf</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/isAttached.html">isAttached</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/isDirty.html">isDirty</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/last.html">last</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/list.html">list</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/listOrderBy.html">listOrderBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/load.html">load</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/lock.html">lock</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/mapWith.html">mapWith</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/mappedBy.html">mappedBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/mapping.html">mapping</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/merge.html">merge</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/namedQueries.html">namedQueries</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/properties.html">properties</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/read.html">read</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/refresh.html">refresh</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/removeFrom.html">removeFrom</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/save.html">save</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/transients.html">transients</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/validate.html">validate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/where.html">where</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/whereAny.html">whereAny</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withCriteria.html">withCriteria</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withNewSession.html">withNewSession</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withSession.html">withSession</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withTransaction.html">withTransaction</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Plug-ins</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Plug-ins/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/URL%20mappings.html">URL mappings</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/codecs.html">codecs</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/controllers.html">controllers</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/core.html">core</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/dataSource.html">dataSource</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/domainClasses.html">domainClasses</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/hibernate.html">hibernate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/i18n.html">i18n</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/logging.html">logging</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/scaffolding.html">scaffolding</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/services.html">services</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/servlets.html">servlets</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Services</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Services/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Services/scope.html">scope</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Services/transactional.html">transactional</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Servlet API</h1><div class="menu-sub">
                        
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/request.html">request</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/response.html">response</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/servletContext.html">servletContext</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/session.html">session</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Tag Libraries</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/actionName.html">actionName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/controllerName.html">controllerName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/flash.html">flash</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/pageScope.html">pageScope</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/params.html">params</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/request.html">request</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/response.html">response</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/servletContext.html">servletContext</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/session.html">session</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Tags</h1><div class="menu-sub">
                        
                            
                            <div class="menu-item"><a href="../ref/Tags/actionSubmit.html">actionSubmit</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/actionSubmitImage.html">actionSubmitImage</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/applyLayout.html">applyLayout</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/checkBox.html">checkBox</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/collect.html">collect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/cookie.html">cookie</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/country.html">country</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/countrySelect.html">countrySelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/createLink.html">createLink</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/createLinkTo.html">createLinkTo</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/currencySelect.html">currencySelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/datePicker.html">datePicker</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/each.html">each</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/eachError.html">eachError</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/else.html">else</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/elseif.html">elseif</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/external.html">external</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/field.html">field</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/fieldError.html">fieldError</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/fieldValue.html">fieldValue</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/findAll.html">findAll</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/form.html">form</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/formatBoolean.html">formatBoolean</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/formatDate.html">formatDate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/formatNumber.html">formatNumber</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/grep.html">grep</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/hasErrors.html">hasErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/header.html">header</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/hiddenField.html">hiddenField</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/if.html">if</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/img.html">img</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/include.html">include</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/isAvailable.html">isAvailable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/isNotAvailable.html">isNotAvailable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/javascript.html">javascript</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/join.html">join</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/layoutBody.html">layoutBody</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/layoutHead.html">layoutHead</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/layoutTitle.html">layoutTitle</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/link.html">link</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/localeSelect.html">localeSelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/message.html">message</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/meta.html">meta</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/pageProperty.html">pageProperty</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/paginate.html">paginate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/passwordField.html">passwordField</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/radio.html">radio</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/radioGroup.html">radioGroup</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/render.html">render</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/renderErrors.html">renderErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/resource.html">resource</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/select.html">select</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/set.html">set</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/sortableColumn.html">sortableColumn</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/submitButton.html">submitButton</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/textArea.html">textArea</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/textField.html">textField</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/timeZoneSelect.html">timeZoneSelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/unless.html">unless</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/uploadForm.html">uploadForm</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/while.html">while</a>
                            </div>
                            
                            </div>
                    </div>
                    
                </div>
            </div>
        </td>
    </tr>
</table>

<div id="footer">
    Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
    
</div>

<script type="text/javascript" src="../js/docs.js"></script>

</body>
</html>
